(object)$arrayの役割

940 ワード

ドメインに定義されたarray変数を適用すると、stdClassオブジェクトが返され、メンバーを自由に追加できます.
<?php
    $test = array('a'=>1,'b'=>2);
    $test = (object)$test;
    echo $test->a;
?>

英語の解釈は以下の通りです.
he PHP stdClass() is something that isn’t well documented but i will try to shed some light into the matter. stdClass is a default PHP object which has no predefined members. The name stdClass is used internally by Zend and is reserved. So that means that you cannot define a class named stdClass in your PHP code.   It can be used to manually instantiate generic objects which you can then set member variables for, this is useful for passing objects to other functions or methods which expect to take an object as an argument. An even more likely usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key in the array.