请定义什么是stdClass。
当前回答
stdClass只是一个通用的“空”类,用于将其他类型强制转换为对象。不管其他两个答案怎么说,stdClass不是PHP中对象的基类。这很容易证明:
class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'
我不相信PHP中有基对象的概念
其他回答
如果您想快速创建一个新对象来保存关于一本书的一些数据。你会这样做:
$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
我们使用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 >
同样值得注意的是,还可以使用json_decode()创建stdClass对象。
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号