请定义什么是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/。

其他回答

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.

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

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

class emp{}

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

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

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

$o = new \stdClass();

等于

const o = {};

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