请定义什么是stdClass。


当前回答

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

例子:

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

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

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

然后PHP将结果放在stdclass中。

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

其他回答

同样的,

$myNewObj->setNewVar = 'newVal'; 

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

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

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

太酷了!

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

stClass是一个由php自己创建的空类,只能由php使用。 因为它不仅仅是一个“空”类, php使用stdClass将数组转换为对象样式 如果你需要使用stdClass,我推荐两个更好的选择: 1-使用数组(比类快得多) 2-创建你自己的空类并使用它

//example 1
$data=array('k1'=>'v1' , 'k2'=>'v2',....);

//example 2
//creating an empty class is faster than instances an stdClass
class data={}
$data=new data();
$data->k1='v1';
$data->k2='v2';

是什么让人们考虑使用对象样式而不是数组样式??

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.

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

例子:

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

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

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

然后PHP将结果放在stdclass中。

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