请定义什么是stdClass。


当前回答

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

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

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

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

我们使用stdClass的原因是在PHP中没有办法区分普通数组和关联数组(就像在Javascript中,你用{}表示对象,用[]表示数组来区分它们)。

这就给空对象带来了一个问题。以这个为例。

PHP:

$a = [1, 2, 3]; // this is an array
$b = ['one' => 1, 'two' => 2]; // this is an associate array (aka hash)
$c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)

让我们假设您想要对变量$c进行JSON编码

echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': {one: 1, two: 2}}

现在假设你删除了b美元的所有键,使它为空。因为$b现在是空的(你删除了所有的键,记得吗?),它看起来像[],如果你看它,它可以是一个数组或对象。

因此,如果再次执行json_encode,输出将有所不同

echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': []}

这是一个问题,因为我们知道b应该是一个关联数组,但PHP(或任何像json_encode这样的函数)不是。

所以stdClass来救场了。再举一个同样的例子

$a = [1, 2, 3]; // this is an array
$b = (object) ['one' => 1, 'two' => 2]; // this makes it an stdClass
$c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)

所以现在即使你删除$b中的所有键并使其为空,因为它是一个stdClass,这并不重要,当你json_encode它时,你会得到这样的结果:

echo json_encode($c);
// outputs => {'a': [1,2,3], 'b': {}}

这也是为什么json_encode和json_decode默认返回stdClass的原因。

 $c = json_decode('{"a": [1,2,3], "b": {}}', true); //true to deocde as array
 // $c is now ['a' => [1,2,3], 'b' => []] in PHP
 // if you json_encode($c) again your data is now corrupted

请记住,两个空的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,并将速度与空类进行比较。

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