PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

변수> <변수형
Last updated: Sun, 25 Nov 2007

view this page in

타입 저글링

PHP는 변수 선언부의 명시적인 타입 정의를 요구하지않는다(지원하지않는다) 변수의 타입은 변수가 사용되는 환경에서 결정된다. 즉, 문자열 값을 변수 $var 에 지정하면,$var 는 문자열이 된다. integer값이 $var 에 지정되면, integer가 된다.

PHP의 자동적인 타입 변환의 예로는 덧셈 연산자 '+'를 들수 있다. 피연산자 중 어느 하나가 float이라면, 모든 피연산자는 float으로 취급된다. 그렇지 않으면, 피연산자는 정수로 해석될것이고, 결과값도 정수가 될것이다. 이런일이 피연산자 자신의 타입을 바꾸지 않는다는 것에 주의하라; 피연산자가 어떻게 평가되느냐에 따라서만 변환이 이루어진다.

<?php
$foo 
"0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo $foo 1.3;  // $foo is now a float (3.3)
$foo "10 Little Piggies"// $foo is integer (15)
$foo "10 Small Pigs";     // $foo is integer (15)
?>

위 예제코드중 마지막 두가지가 이상해 보인다면, 문자열을 수로 변환을 참고.

어떤 변수를 특정 타입으로 취급하고자 한다면, 타입 캐스트 매뉴얼 섹션을 참고할것. 변수의 타입을 변환하려고 하면, settype()를 볼것.

이 섹션에서 다른 에제를 테스트하기 위해 var_dump() 함수를 사용할수 있다.

Note: 배열의 자동적인 변환 방식은 현재까지 정의되지 않았다.

<?php
$a 
"1";     // $a is a string
$a[0] = "f";  // What about string offsets? What happens?
?>

PHP는 배열 인덱싱과 같은 문법을 사용하여 오프셋을 통하여 문자열 안의 인덱싱을 지원하기 때문에(역사적인이유로), 위 예제코드는 문제가 될 소지가 있다: $a는 그 첫번째 요소가 "f"를 갖는 배열이 되는가? "f"가 문자열 $a 문자열의 첫번째 문자가 되는가?
현재 버전 PHP는 두번째 할당문을 문자열 오프셋 인식으로 해석한다. 그래서 $a는 "f"가 되고, 자동 변환의 결과는 정의되지 않은것으로 여겨진다. PHP 4는 스트링 내의 문자에 접근하기 위한 중괄호 문법을 새로이 제공한다. 위에서 제시한것 대신 이문법을 사용하도록 한다
<?php
$a    
"abc"// $a is a string
$a{1} = "f";   // $a is now "afc"
?>
자세한 정보는 문자열의 문자 접근과 변경섹션을 참고.

타입 캐스트

PHP에서 타입 캐스느는 C에서 동작하는 것과 유사하게 동작한다. 원하는 타입의 이름을 변수 앞 괄호안에 사용하여 캐스트될수 있다.

<?php
$foo 
10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

허용되는 캐스트는 다음과 같다:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object

탭과 빈칸이 괄호안에서 허용된다는것에 주의한다. 그래서 다음 예는 기능적으로 동일하다:

<?php
$foo 
= (int) $bar;
$foo = ( int ) $bar;
?>

Note: 변수를 문자열로 캐스트하는 대신에, 큰 따옴표 안에 변수를 넣어줄수도 있다.

<?php
$foo 
10;            // $foo is an integer
$str "$foo";        // $str is a string
$fst = (string) $foo// $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo 
"they are the same";
}
?>

특정 타입간의 캐스트가 될때 무슨일이 일어날지 여기서 명확하지 않으면 자세한 정보를 보기 위해 아래 섹션을 참고.



변수> <변수형
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
타입 저글링
alexgr at gmail dot com
20-Jun-2008 03:43
For a Cast to a User Defined Object you can define a cast method:

class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
}

In your php page code you can:
$myObject = MyObject::cast($_SESSION["myObject"]);

Then, PHP will validate the value and your IDE will help you.
miracle at 1oo-percent dot de
20-Feb-2006 05:26
If you want to convert a string automatically to float or integer (e.g. "0.234" to float and "123" to int), simply add 0 to the string - PHP will do the rest.

e.g.

$val = 0 + "1.234";
(type of $val is float now)

$val = 0 + "123";
(type of $val is integer now)
22-Jun-2005 05:47
If you have a boolean, performing increments on it won't do anything despite it being 1.  This is a case where you have to use a cast.

<html>
<body> <!-- don't want w3.org to get mad... -->
<?php
$bar
= TRUE;
?>
I have <?=$bar?> bar.
<?php
$bar
++;
?>
I now have <?=$bar?> bar.
<?php
$bar
= (int) $bar;
$bar++;
?>
I finally have <?=$bar?> bar.
</body>
</html>

That will print

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
toma at smartsemantics dot com
09-Mar-2005 06:24
In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes.  It also makes use of some regular expression matching rather than string position, replacing, etc.  It takes an object ($obj) of any type and casts it to an new type ($class_type).  Note that the new class type must exist:

function ClassTypeCast(&$obj,$class_type){
    if(class_exists($class_type,true)){
        $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i",
          "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));
    }
}
Raja
10-Feb-2005 03:05
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667
tom5025_ at hotmail dot com
24-Aug-2004 01:27
function strhex($string)
{
   $hex="";
   for ($i=0;$i<strlen($string);$i++)
       $hex.=dechex(ord($string[$i]));
   return $hex;
}
function hexstr($hex)
{
   $string="";
   for ($i=0;$i<strlen($hex)-1;$i+=2)
       $string.=chr(hexdec($hex[$i].$hex[$i+1]));
   return $string;
}

to convert hex to str and vice versa
dimo dot vanchev at bianor dot com
10-Mar-2004 07:02
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-2004 02:08]
didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.
Anyway here's what I wrote to solve the long_named_classes problem:

<?php
function typecast($old_object, $new_classname) {
    if(
class_exists($new_classname)) {
       
$old_serialized_object = serialize($old_object);
       
$old_object_name_length = strlen(get_class($old_object));
       
$subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;
       
$new_serialized_object  = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';
       
$new_serialized_object .= substr($old_serialized_object, $subtring_offset);
        return
unserialize($new_serialized_object);
     } else {
         return
false;
     }
}
?>
philip_snyder at hotmail dot com
27-Feb-2004 07:08
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    // Example serialized object segment
    // O:5:"field":9:{s:5:...   <--- Class: Field
    $old_serialized_prefix  = "O:".strlen(get_class($old_object));
    $old_serialized_prefix .= ":\"".get_class($old_object)."\":";

    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';
    $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
post_at_henribeige_dot_de
03-May-2003 09:37
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
                             substr($old_serialized_object, $old_serialized_object[2] + 7);
    return unserialize($new_serialized_object);
  }
  else
    return false;
}

Example:

class A {
  var $secret;
  function A($secret) {$this->secret = $secret;}
  function output() {echo("Secret class A: " . $this->secret);}
}

class B extends A {
  var $secret;
  function output() {echo("Secret class B: " . strrev($this->secret));}
}

$a = new A("Paranoia");
$b = typecast($a, "B");

$a->output();
$b->output();
echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));

Output of the example code above:

Secret class A: Paranoia
Secret class B: aionaraP
Classname $a: a
Classname $b: b
yury at krasu dot ru
27-Nov-2002 01:24
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:

$a = TRUE;
echo ($a++).$a;  // prints "11"
28-Aug-2002 10:26
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:
(string)TRUE //returns "1"
(string)FALSE //returns ""
echo TRUE; //prints "1"
echo FALSE; //prints nothing!

변수> <변수형
Last updated: Sun, 25 Nov 2007
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites