Sunday, March 25, 2007

Converting to object(String,Array)

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built in class is created. If the value was NULL, the new instance will be empty. Array converts to an object with properties named by array keys and with corresponding values. For any other value, a member variable named scalar will contain the value.


<br/>
<?php
$bar = "boo";
$obj = (object) $bar;
var_dump($obj);// object(stdClass)#1 (1) { ["scalar"]=> string(3) "boo" }
echo "<br/>";

$arr = array('x' => 1, 'y' => 2, 'z' => 3);

$obj_arr = (object) $arr;
var_dump($arr); //array(3) { ["x"]=> int(1) ["y"]=> int(2) ["z"]=> int(3) }
var_dump($obj_arr); //object(stdClass)#2 (3) { ["x"]=> int(1) ["y"]=> int(2) ["z"]=> int(3) }
echo "<br/>";

$var = 'x';
echo $obj_arr->x; // 1
echo "<br/>";
echo $obj_arr->$var; // 1
?>

No comments :