请定义什么是stdClass。


当前回答

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不是匿名类或匿名对象

这里的答案包括stdClass是匿名类甚至匿名对象的表达式。这不是真的。

stdClass只是一个常规的预定义类。你可以使用instanceof操作符或函数get_class来检查。这里没什么特别的。PHP在将其他值强制转换为对象时使用这个类。

在程序员使用stdClass的许多情况下,数组是更好的选择,因为它有有用的函数,而且这个用例表示的是数据结构,而不是真正的对象。

正在使用的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 = {};

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

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

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

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

使用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文档中的这个示例以进一步了解。