请定义什么是stdClass。


当前回答

同样值得注意的是,还可以使用json_decode()创建stdClass对象。

其他回答

stdClass在PHP中是经典的泛型类。它没有内置的属性或方法。基本上,它用于类型转换,创建具有动态属性的对象等。如果您有javascript背景,您可以确定为

$o = new \stdClass();

等于

const o = {};

它创建空对象,稍后由程序控制流填充。

同样值得注意的是,通过使用Casting,你实际上不需要像@Bandula给出的答案那样创建一个对象。相反,您可以简单地将数组强制转换为对象并返回stdClass。例如:

$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

$obj = (object) $array;
echo $obj->Property3;

再次输出:

同样值得注意的是,还可以使用json_decode()创建stdClass对象。

如果您想快速创建一个新对象来保存关于一本书的一些数据。你会这样做:

$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/。

同样的,

$myNewObj->setNewVar = 'newVal'; 

生成一个stdClass对象-自动强制转换

我今天把这个单词拼错了:

$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';

太酷了!