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

search for in the

変数> <
Last updated: Fri, 14 Nov 2008

view this page in

型の相互変換

PHP は、変数定義時に明示的な型定義を必要と(または、サポート) しません。ある変数の型は、その変数が使用される文により定義されます。 これは、ある文字列を変数 var に代入した場合には、 var は文字列になることを意味しています。 ある整数値を var に代入した場合には、 その変数は整数になります。

PHP の自動型変換の例の一つは、加算演算子 '+' です。 オペランドのどれかが float の場合、全てのオペランドは float として評価され、結果は float になります。 その他の場合、オペランドは整数として解釈され、結果も整数になります。 この自動型変換は、 オペランド自体の型を変更するものではないということに注意してください。 変わるのは、オペランドがどのように評価されるかだけです。

<?php
$foo 
"0";  // $foo は文字列です (ASCII 48)
$foo += 2;   // ここでは、$foo は整数です (2)
$foo $foo 1.3;  // ここでは、$foo はfloatです (3.3)
$foo "10 Little Piggies"// $foo は整数です (15)
$foo "10 Small Pigs";     // $foo は整数です (15)
?>

最後の二つの例が奇妙に思える場合には、 文字列変換 を参照ください。

ある変数を強制的にある特定の型として評価させたい場合には、 型キャスト のセクションを参照ください。ある変数の型を変更したい場合には、 settype() を参照してください。

本節の例をテストしたい場合には、 var_dump() を使用することが可能です。

注意: 配列への自動変換の動作は現時点で定義されていません。
また、PHP では配列の添字と同じ構文を使用した文字列へのアクセスをサポートしているので、 次の例はあらゆるバージョンの PHP で成立します。

<?php
$a    
'car'// $a は文字列です
$a[0] = 'b';   // $a はここでも文字列です
echo $a;       // bar
?>
詳細は、 文字として文字列をアクセスするというセクションを参照してください。

型キャスト

PHP の型キャストは、C 言語と同様に動作します。つまり、 変換しようとする型を括弧で括り、キャストする変数の前に置きます。

<?php
$foo 
10;   // $foo は整数です
$bar = (boolean) $foo;   // $bar はbooleanです
?>

使用可能なキャストを以下に示します。

  • (int), (integer) - 整数へのキャスト
  • (bool), (boolean) - 論理値へのキャスト
  • (float), (double), (real) - float へのキャスト
  • (string) - 文字列へのキャスト
  • (binary) - バイナリ文字列へのキャスト (PHP 6)
  • (array) - 配列へのキャスト
  • (object) - オブジェクトへのキャスト
  • (unset) - NULL へのキャスト (PHP 5)

(binary) によるキャストや b プレフィックスのサポートは、PHP 5.2.1 で追加されました。

括弧の中でタブとスペースを使用することができることに注意してください。 したがって、次の文は機能的に等価です。

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

リテラル文字列や変数を、バイナリ文字列にキャストします。

<?php
$binary 
= (binary)$string;
$binary b"binary string";
?>

注意: ある変数を文字列にキャストする代わりに、 二重引用符で括ることもできます。

<?php
$foo 
10;            // $foo は整数です
$str "$foo";        // $str は文字列です
$fst = (string) $foo// $fst も文字列です

// これは、"they are the same"を出力します
if ($fst === $str) {
    echo 
"they are the same";
}
?>

型の間でキャストを行う際の動作は、必ずしも明確ではありません。 詳細については、以下の節を参照ください。



変数> <
Last updated: Fri, 14 Nov 2008
 
add a note add a note User Contributed Notes
型の相互変換
kajsunansis at that gmail
03-Dec-2008 09:18
json_decode users consider this, when casting stdClass to array:
<?php
$obj
= new stdClass();
$obj->{"2"} = "id";
$arr = (array) $obj;
$result = isset($arr["2"]) || array_key_exists(2, $arr); // false
?>
..though casting is at least 2x faster than foreach.
Jeffrey
09-Nov-2008 09:34
IMAGINATION REQUIRED...

We can be a witness to PHP's 'type-jugglin' in real-time with a simple implementation of a MemoryMap. For the sake our purposes, pretend that this is an empty MemoryMap.
+-------+------+------+-------+
| index | $var | type | value |
+-------+------+------+-------+
|     1 |  --- | NULL |  null |
|     2 |  --- | NULL |  null |
|     3 |  --- | NULL |  null |
|     4 |  --- | NULL |  null |
+-------+------+------+-------+

<?php
# create some variables...
$a = 10;
$b = "Hello";
$c = array(55.45, 98.65);
# Now look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a | INTEGER |     10 |
|     2 |    $b |  STRING |  Hello |
|     3 | $c[0] |   FLOAT |  55.45 |
|     4 | $c[1] |   FLOAT |  98.65 |
+-------+-------+---------+--------+
<?php
# Now, change the variable types...
$a = "Bye";
$b = 2;
$c[0] = "Buy";
$c[1] = "Now!";
#Look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a |  STRING |    Bye | <- used to be INTEGER
|     2 |    $b | INTEGER |      2 | <- used to be STRING
|     3 | $c[0] |  STRING |    Buy | <- used to be FLOAT
|     4 | $c[1] |  STRING |  Right | <- used to be FLOAT
+-------+-------+---------+--------+
hek at theeks dot net
04-Nov-2008 07:22
The behavior of comparisons between objects of different types is, in fact, already documented (though a cross-reference from this page might be handy for future readers):

http://www.php.net/manual/en/language.operators.comparison.php
hek at theeks dot net
17-Oct-2008 07:24
It would be useful to know the precedence (for lack of a better word) for type juggling.  This entry currently explains that "if either operand is a float, then both operands are evaluated as floats, and the result will be a float" but could (and I think should) provide a hierarchy that indicates, for instance, "between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins" and so on (and don't count on my example accurately capturing the true hierarchy, as I haven't actually done the tests to figure it out).  Thanks!
wbcarts at juno dot com
08-Oct-2008 04:05
WHERE'S THE BEEF?

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin' less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
<?php
class Point {
 
protected $x, $y;

 
public function __construct($xVal = 0, $yVal = 0) {
   
$this->x = $xVal;
   
$this->y = $yVal;
  }
 
public function getX() { return $this->x; }
 
public function getY() { return $this->y; }
}

$p = new Point(25, 35);
echo
$p->getX();      // 25
echo $p->getY();      // 35
?>
Ok, now we need extra powers. PHP gives us several options:
  A. We can tag on extra properties on-the-fly using everyday PHP syntax...
    $p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it's on a per-instance basis, blah.
  B. We can try type-casting it to a different type to access more functions...
    $p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with... and just like above, this only works on a per-instance basis.
  C. Do it the right way using OOP - and just extend the Point class already.
<?php
class Point3D extends Point {
 
protected $z;                                // add extra properties...

 
public function __construct($xVal = 0, $yVal = 0, $zVal = 0) {
   
parent::__construct($xVal, $yVal);
   
$this->z = $zVal;
  }
 
public function getZ() { return $this->z; }  // add extra functions...
}

$p3d = new Point3D(25, 35, 45);  // more data, more functions, more everything...
echo $p3d->getX();               // 25
echo $p3d->getY();               // 35
echo $p3d->getZ();               // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any "single lesser object" on-the-fly, and it's way easier to do.
lucazd at gmail dot com
24-Sep-2008 07:20
@alexgr (20-Jun-2008)

Correct me if I'm wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what's really happening:

<?php
class MyObject {
   
/**
     * @param MyObject $object
     * @return MyObject
     */
   
static public function cast(MyObject $object) {
        return
$object;
    }
   
/** Does nothing */
   
function f() {}
}

class
X extends MyObject {
   
/** Throws exception */
   
function f() { throw new exception(); }
}

$x = MyObject::cast(new X);
$x->f(); // Your IDE tells 'f() Does nothing'
?>

However, when you run the script, you will get an exception.
r dot nox at bk dot ru
22-Sep-2008 10:04
$j = 1;
print('a' . $j+1);

Will print:

1
nullhilty at gmail dot com
09-Sep-2008 09:34
Just a little experiment on the (unset) type cast:

<?php
$var
= 1;
$var_unset = (unset) $var;
$var_ref_unset &= (unset) $var;
var_dump($var);
var_dump($var_unset);
var_dump($var_ref_unset);
?>

output:
int(1)
NULL
int(0)
alexgr at gmail dot com
20-Jun-2008 01: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 03: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)
23-Jun-2005 03: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
10-Mar-2005 04: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 01: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 11: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 05: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 05: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 07: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 11: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"
29-Aug-2002 08: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: Fri, 14 Nov 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites