请定义什么是stdClass。


当前回答

同样的,

$myNewObj->setNewVar = 'newVal'; 

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

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

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

太酷了!

其他回答

使用stdClass,您可以创建一个具有自己属性的新对象。 考虑以下示例,该示例将用户的详细信息表示为关联数组。

$array_user = array();
$array_user["name"] = "smith john";
$array_user["username"] = "smith";
$array_user["id"] = "1002";
$array_user["email"] = "smith@nomail.com";

如果需要表示与对象属性相同的细节,可以如下所示使用stdClass。

$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";

如果您是Joomla开发人员,请参考Joomla文档中的这个示例以进一步了解。

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

例子:

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

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

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

然后PHP将结果放在stdclass中。

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

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

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

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

正在使用的stdClass对象

stdClass允许您创建匿名类和 使用对象类型转换,您还可以以OOP样式访问关联数组的键。就像访问普通的object属性一样。

例子

class Example {

  private $options;

  public function __construct(Array $setup)
  {
    // casting Array to stdClass object
    $this->options = (object) $setup;

    // access stdClass object in oop style - here transform data in OOP style using some custom method or something...
    echo $this->options->{'name'}; // ->{'key'}
    echo $this->options->surname;  // ->key
  }

}

$ob1 = new Example(["name" => "John", "surname" => "Doe"]);

将回声

John Doe

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