请定义什么是stdClass。


当前回答

Stdclass是一种当某些数据必须放在类中时PHP避免停止解释脚本的方法,但是 不幸的是,这个类没有定义

例子:

 return $statement->fetchAll(PDO::FETCH_CLASS  , 'Tasks');

在这里,数据将放在预定义的“任务”中。但是,如果我们这样做代码:

 return $statement->fetchAll(PDO::FETCH_CLASS );

然后PHP将结果放在stdclass中。

简单的php说:看,我们有一个好的孩子[对象]在这里,但没有父母。所以,我们会把他们送到一个婴幼儿护理之家标准班:)

其他回答

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

同样的,

$myNewObj->setNewVar = 'newVal'; 

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

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

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

太酷了!

stdClass不是匿名类或匿名对象

这里的答案包括stdClass是匿名类甚至匿名对象的表达式。这不是真的。

stdClass只是一个常规的预定义类。你可以使用instanceof操作符或函数get_class来检查。这里没什么特别的。PHP在将其他值强制转换为对象时使用这个类。

在程序员使用stdClass的许多情况下,数组是更好的选择,因为它有有用的函数,而且这个用例表示的是数据结构,而不是真正的对象。

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

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

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

再次输出:

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.