请定义什么是stdClass。
当前回答
stdClass是PHP的泛型空类,有点像Java中的Object或Python中的Object(编辑:但实际上不用作通用基类;谢谢@Ciaran指出这一点)。
它对于匿名对象、动态属性等非常有用。
考虑StdClass的一个简单方法是作为关联数组的替代。请参阅下面的示例,该示例展示了json_decode()如何允许获取StdClass实例或关联数组。 SoapClient::__soapCall返回一个StdClass实例,但在本例中没有显示。
<?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中的动态属性。
其他回答
使用stdClass,您可以创建一个具有自己属性的新对象。 考虑以下示例,该示例将用户的详细信息表示为关联数组。
$array_user = array();
$array_user["name"] = "smith john";
$array_user["username"] = "smith";
$array_user["id"] = "1002";
$array_user["email"] = "smith@nomail.com";
如果需要表示与对象属性相同的细节,可以如下所示使用stdClass。
$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";
如果您是Joomla开发人员,请参考Joomla文档中的这个示例以进一步了解。
请记住,两个空的stdclass并不是严格相等的。在编写嘲弄期望时,这一点非常重要。
php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >
同样值得注意的是,还可以使用json_decode()创建stdClass对象。
同样的,
$myNewObj->setNewVar = 'newVal';
生成一个stdClass对象-自动强制转换
我今天把这个单词拼错了:
$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';
太酷了!
如果您想快速创建一个新对象来保存关于一本书的一些数据。你会这样做:
$book = new stdClass;
$book->title = "Harry Potter and the Prisoner of Azkaban";
$book->author = "J. K. Rowling";
$book->publisher = "Arthur A. Levine Books";
$book->amazon_link = "http://www.amazon.com/dp/0439136369/";
详情请查看网站http://www.webmaster-source.com/2009/08/20/php-stdclass-storing-data-object-instead-array/。
推荐文章
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?
- 当使用Composer的开发/生产开关时,如何正确部署?
- 自动删除Laravel (Eloquent ORM)中的相关行
- 在取消设置元素后重新设置数组键
- 如何修剪空白的数组值在php
- PHP中的双not(!!)操作符
- 在PHP5中创建单例设计模式
- 阻止人们入侵基于php的Flash游戏高分表的最佳方法是什么
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串