问题描述
请定义 stdClass
是什么.
推荐答案
stdClass
是 PHP 的通用空类,有点像 Java 中的 Object
或 object
在 Python 中( 但实际上并未用作通用基类;感谢 @Ciaran 指出这一点).
stdClass
is PHP's generic empty class, kind of like Object
in Java or object
in Python ( but not actually used as universal base class; thanks @Ciaran for pointing this out).
对于匿名对象、动态属性等很有用
It is useful for anonymous objects, dynamic properties, etc.
考虑 StdClass 的一种简单方法是作为关联数组的替代方案.请参阅下面的示例,该示例显示了 json_decode()
如何允许获取 StdClass 实例或关联数组.同样,但在本例中没有显示,SoapClient::__soapCall
返回一个 StdClass 实例.
An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode()
allows to get an StdClass instance or an associative array.Also but not shown in this example, SoapClient::__soapCall
returns an StdClass instance.
<?php
//Example with StdClass
$json = '{ "foo": "bar", "number": 42 }';
$stdInstance = json_decode($json);
echo $stdInstance->foo . PHP_EOL; //"bar"
echo $stdInstance->number . PHP_EOL; //42
//Example with associative array
$array = json_decode($json, true);
echo $array['foo'] . PHP_EOL; //"bar"
echo $array['number'] . PHP_EOL; //42
有关更多示例,请参阅PHP 和 StdClass 中的动态属性.
See Dynamic Properties in PHP and StdClass for more examples.
这篇关于PHP 中的 stdClass 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!