请定义什么是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 = {};
它创建空对象,稍后由程序控制流填充。
推荐文章
- 在取消设置元素后重新设置数组键
- 如何修剪空白的数组值在php
- PHP中的双not(!!)操作符
- 在PHP5中创建单例设计模式
- 阻止人们入侵基于php的Flash游戏高分表的最佳方法是什么
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串
- __construct函数的作用是什么?
- PHP中的异步shell执行器
- Laravel 5 -如何访问在视图存储上传的图像?
- 为什么在PHP中使用sprintf函数?
- “质量分配”在Laravel中是什么意思?
- 在逗号上爆炸字符串,并修剪每个值的潜在空格
- PHP与MySQL 8.0+错误:服务器请求身份验证方法未知的客户端
- laravel5“LIKE”对等物(雄辩的)
- 在函数中使用默认实参