php php创建没有类的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14395631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php create object without class
提问by Wolfgang Adamec
Possible Duplicate:
Creating anonymous objects in php
可能的重复:
在 php 中创建匿名对象
In JavaScript, you can easiliy create an object without a class by:
在 JavaScript 中,您可以通过以下方式轻松创建没有类的对象:
myObj = {};
myObj.abc = "aaaa";
For PHP I've found this one, but it is nearly 4 years old: http://www.subclosure.com/php-creating-anonymous-objects-on-the-fly.html
对于 PHP,我找到了这个,但它已经有将近 4 年的历史了:http: //www.subclosure.com/php-creating-anonymous-objects-on-the-fly.html
$obj = (object) array('foo' => 'bar', 'property' => 'value');
Now with PHP 5.4 in 2013, is there an alternative to this?
现在在 2013 年使用 PHP 5.4,是否有替代方案?
回答by Artem L
you can always use new stdClass(). Example code:
您可以随时使用new stdClass(). 示例代码:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
同样从 PHP 5.4 开始,您可以获得相同的输出:
$object = (object) ['property' => 'Here we go'];

