请定义什么是stdClass。


当前回答

php.net手册有一些可靠的解释和例子,用户贡献的stdClass是什么,我特别喜欢这个http://php.net/manual/en/language.oop5.basic.php#92123, https://stackoverflow.com/a/1434375/2352773。

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces. When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance. stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect. You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

其他回答

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

同样的,

$myNewObj->setNewVar = 'newVal'; 

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

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

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

太酷了!

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

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

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

再次输出:

实际上,我尝试创建空的stdClass,并将速度与空类进行比较。

class emp{}

然后继续创建1000个stdClasses和emps…空类在1100微秒左右完成,而stdClasses在1700微秒以上完成。所以我想最好创建自己的虚拟类来存储数据,如果你想使用对象那么糟糕(数组写和读都快得多)。

stdClass只是一个通用的“空”类,用于将其他类型强制转换为对象。不管其他两个答案怎么说,stdClass不是PHP中对象的基类。这很容易证明:

class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'

我不相信PHP中有基对象的概念