请定义什么是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.
其他回答
stClass是一个由php自己创建的空类,只能由php使用。 因为它不仅仅是一个“空”类, php使用stdClass将数组转换为对象样式 如果你需要使用stdClass,我推荐两个更好的选择: 1-使用数组(比类快得多) 2-创建你自己的空类并使用它
//example 1
$data=array('k1'=>'v1' , 'k2'=>'v2',....);
//example 2
//creating an empty class is faster than instances an stdClass
class data={}
$data=new data();
$data->k1='v1';
$data->k2='v2';
是什么让人们考虑使用对象样式而不是数组样式??
stdClass是PHP的泛型空类,有点像Java中的Object或Python中的Object(编辑:但实际上不用作通用基类;谢谢@Ciaran指出这一点)。
它对于匿名对象、动态属性等非常有用。
考虑StdClass的一个简单方法是作为关联数组的替代。请参阅下面的示例,该示例展示了json_decode()如何允许获取StdClass实例或关联数组。 SoapClient::__soapCall返回一个StdClass实例,但在本例中没有显示。
<?php
//Example with StdClass
$json = '{ "foo": "bar", "number": 42 }';
$stdInstance = json_decode($json);
echo $stdInstance->foo . PHP_EOL; //"bar"
echo $stdInstance->number . PHP_EOL; //42
//Example with associative array
$array = json_decode($json, true);
echo $array['foo'] . PHP_EOL; //"bar"
echo $array['number'] . PHP_EOL; //42
更多示例请参见PHP和StdClass中的动态属性。
stdClass只是一个通用的“空”类,用于将其他类型强制转换为对象。不管其他两个答案怎么说,stdClass不是PHP中对象的基类。这很容易证明:
class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N';
// outputs 'N'
我不相信PHP中有基对象的概念
同样的,
$myNewObj->setNewVar = 'newVal';
生成一个stdClass对象-自动强制转换
我今天把这个单词拼错了:
$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';
太酷了!
正在使用的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
推荐文章
- 在取消设置元素后重新设置数组键
- 如何修剪空白的数组值在php
- PHP中的双not(!!)操作符
- 在PHP5中创建单例设计模式
- 阻止人们入侵基于php的Flash游戏高分表的最佳方法是什么
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串
- __construct函数的作用是什么?
- PHP中的异步shell执行器
- Laravel 5 -如何访问在视图存储上传的图像?
- 为什么在PHP中使用sprintf函数?
- “质量分配”在Laravel中是什么意思?
- 在逗号上爆炸字符串,并修剪每个值的潜在空格
- PHP与MySQL 8.0+错误:服务器请求身份验证方法未知的客户端
- laravel5“LIKE”对等物(雄辩的)
- 在函数中使用默认实参