请定义什么是stdClass。


当前回答

同样的,

$myNewObj->setNewVar = 'newVal'; 

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

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

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

太酷了!

其他回答

请记住,两个空的stdclass并不是严格相等的。在编写嘲弄期望时,这一点非常重要。

php > $a = new stdClass();
php > $b = new stdClass();
php > var_dump($a === $b);
bool(false)
php > var_dump($a == $b);
bool(true)
php > var_dump($a);
object(stdClass)#1 (0) {
}
php > var_dump($b);
object(stdClass)#2 (0) {
}
php >

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

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

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

再次输出:

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

例子:

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

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

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

然后PHP将结果放在stdclass中。

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

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

class emp{}

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

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

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