PHPダイナミックプロパティとstdclass


動的属性はPHP固有ではなく、javascriptなどの解釈型言語にこの機能があることが多い.オブジェクトの削除プロパティを動的に追加できます.PHPは、次の例のようにプロパティを動的に追加することもできます.
class testClass
{
public $A='a';
}
$t=new testClass();
echo $t->A,'
'; echo 'B isset=',isset($t->B)?'Y':'N','
';//$t B $t->B='b';//$t B, 。 echo 'B isset=',isset($t->B)?'Y':'N','
'; echo '$t->B=',$t->B,'
'; unset($t->B);//$t B。 echo 'B isset=',isset($t->B)?'Y':'N','
';

これはPHPの中のマジックの方法を思い出させます.getと_set、この2つのマジック方法もこのような機能を完成することができますが、彼らを使うと複雑に見えます.そのため、いくつかの複雑な場合にのみこのマジック方法が使用されます.
このようなダイナミックプロパティを追加する能力があれば、空のクラスを定義し、いつでもどこでも、プロパティを使用するときに自動的に追加することができ、便利です.
このダイナミックプロパティを追加する能力は、タイプ変換時に役立ちます.タイプ変換ではstdClassに言及せざるを得ません.これはPHPに保持されているクラスです.公式ドキュメントはこのstdClassについてあまり説明されていません.以下の公式文書の説明:
Converting to object
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. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.
scalar;  // outputs 'ciao'     
?>

簡単に言えば、あるタイプの値がオブジェクトに変換されるとstdClassのインスタンスが作成されます.ドキュメントに示す例を見て、スカラータイプの値をobjectに変換します.
さらに、次のコードを実行します.
echo '$obj instanceof stdClass=',($obj instanceof stdClass)?'Y':'N','
';

結果は次のとおりです.
$obj instanceof stdClass=Y
つまり、オブジェクトに変換するときにstdClassを作成し、プロパティを動的に追加して値を割り当てます.var_でdumpメソッドからもタイプがstdClassであることがわかる.
理論的にはstdClassを手動でインスタンス化しvar_dumpは彼を見た.

得られた結果は
object(stdClass)[1]
    stdClass            ,       。
      stdClass  C#  object,  PHP         stdClass,     ,            。
class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
stdClass PHP   ,                 ,              ,   ,                 。

参照ドキュメント:
http://krisjordan.com/dynamic-properties-in-php-with-stdclass
http://php.net/manual/en/language.types.object.php