请定义什么是stdClass。


当前回答

stdClass在PHP中是经典的泛型类。它没有内置的属性或方法。基本上,它用于类型转换,创建具有动态属性的对象等。如果您有javascript背景,您可以确定为

$o = new \stdClass();

等于

const o = {};

它创建空对象,稍后由程序控制流填充。

其他回答

请记住,两个空的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 >

stdClass是PHP的泛型空类,有点像Java中的Object或Python中的Object(编辑:但实际上不用作通用基类;谢谢@Ciaran指出这一点)。

它对于匿名对象、动态属性等非常有用。

考虑StdClass的一个简单方法是作为关联数组的替代。请参阅下面的示例,该示例展示了json_decode()如何允许获取StdClass实例或关联数组。 SoapClient::__soapCall返回一个StdClass实例,但在本例中没有显示。

<?php
//Example with StdClass
$json = '{ "foo": "bar", "number": 42 }';
$stdInstance = json_decode($json);
echo $stdInstance->foo . PHP_EOL; //"bar"
echo $stdInstance->number . PHP_EOL; //42
//Example with associative array
$array = json_decode($json, true);
echo $array['foo'] . PHP_EOL; //"bar"
echo $array['number'] . PHP_EOL; //42

更多示例请参见PHP和StdClass中的动态属性。

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

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

正在使用的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

你也可以使用object将数组强制转换为你选择的对象:

Class Example
{
   public $name;
   public $age;
}

现在要创建一个Example类型的对象并初始化它,你可以做以下任何一件事:

$example = new Example();
$example->name = "some name";
$example->age = 22;

OR

$example = new Example();
$example = (object) ['name' => "some name", 'age' => 22];

第二种方法主要用于初始化具有许多属性的对象。