请定义什么是stdClass。
当前回答
stdClass只是一个通用的“空”类,用于将其他类型强制转换为对象。不管其他两个答案怎么说,stdClass不是PHP中对象的基类。这很容易证明:
class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'
我不相信PHP中有基对象的概念
其他回答
stdClass只是一个通用的“空”类,用于将其他类型强制转换为对象。不管其他两个答案怎么说,stdClass不是PHP中对象的基类。这很容易证明:
class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'
我不相信PHP中有基对象的概念
如果您想快速创建一个新对象来保存关于一本书的一些数据。你会这样做:
$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/。
同样值得注意的是,还可以使用json_decode()创建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不是匿名类或匿名对象
这里的答案包括stdClass是匿名类甚至匿名对象的表达式。这不是真的。
stdClass只是一个常规的预定义类。你可以使用instanceof操作符或函数get_class来检查。这里没什么特别的。PHP在将其他值强制转换为对象时使用这个类。
在程序员使用stdClass的许多情况下,数组是更好的选择,因为它有有用的函数,而且这个用例表示的是数据结构,而不是真正的对象。
推荐文章
- 在取消设置元素后重新设置数组键
- 如何修剪空白的数组值在php
- PHP中的双not(!!)操作符
- 在PHP5中创建单例设计模式
- 阻止人们入侵基于php的Flash游戏高分表的最佳方法是什么
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串
- __construct函数的作用是什么?
- PHP中的异步shell执行器
- Laravel 5 -如何访问在视图存储上传的图像?
- 为什么在PHP中使用sprintf函数?
- “质量分配”在Laravel中是什么意思?
- 在逗号上爆炸字符串,并修剪每个值的潜在空格
- PHP与MySQL 8.0+错误:服务器请求身份验证方法未知的客户端
- laravel5“LIKE”对等物(雄辩的)
- 在函数中使用默认实参