PHP 对象字面量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9644870/
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 object literal
提问by TMS
In PHP, I can specify array literals quite easily:
在 PHP 中,我可以很容易地指定数组文字:
array(
array("name" => "John", "hobby" => "hiking"),
array("name" => "Jane", "hobby" => "dancing"),
...
)
But what if I want array of objects? How can I specify object literal in PHP? I.e. in javascript it would be:
但是如果我想要对象数组呢?如何在 PHP 中指定对象字面量?即在javascript中它将是:
[
{name: "John", hobby: "hiking"},
{name: "Jane", hobby: "dancing"}
]
回答by Tim
As BoltClock mentioned there is no object literal in PHP however you can do this by simply type casting the arrays to objects:
正如 BoltClock 所提到的,PHP 中没有对象文字,但是您可以通过简单地将数组类型转换为对象来实现:
$testArray = array(
(object)array("name" => "John", "hobby" => "hiking"),
(object)array("name" => "Jane", "hobby" => "dancing")
);
echo "Person 1 Name: ".$testArray[0]->name;
echo "Person 2 Hobby: ".$testArray[1]->hobby;
回答by mipa
As of PHP 5.4 you can also use the short array syntax:
从 PHP 5.4 开始,您还可以使用短数组语法:
$json = [
(object) ['name' => 'John', 'hobby' => 'hiking'],
(object) ['name' => 'Jane', 'hobby' => 'dancing'],
];
回答by Josh
As others have noted, there is no object literal in PHP, but you can "fake" it by casting an array to an object.
正如其他人所指出的,PHP 中没有对象文字,但您可以通过将数组转换为对象来“伪造”它。
With PHP 5.4, this is even more concise, because arrays can be declared with square brackets. For example:
在 PHP 5.4 中,这更加简洁,因为数组可以用方括号声明。例如:
$obj = (object)[
"foo" => "bar",
"bar" => "foo",
];
This would give you an object with "foo" and "bar" properties. However, I don't think this really provides much advantage over using associative arrays. It's just a syntax difference.
这将为您提供一个具有“foo”和“bar”属性的对象。但是,我认为这与使用关联数组相比并没有真正提供太多优势。这只是一个语法差异。
Consider embracing the uniqueness and "flavor" of all the languages you use. In JavaScript, object literals are all over the place. In PHP, associative arrays are functionally the same as JavaScript object literals, are easy to create, and are well understood by other PHP programmers. I think you're better off embracing this "flavor" than trying to make it feel like JavaScript's object literal syntax.
考虑拥抱您使用的所有语言的独特性和“风味”。在 JavaScript 中,对象字面量无处不在。在 PHP 中,关联数组在功能上与 JavaScript 对象字面量相同,易于创建,并且为其他 PHP 程序员所熟知。我认为你最好接受这种“风格”,而不是试图让它感觉像 JavaScript 的对象字面量语法。
回答by Septagram
Another way would be to use the __set_state()
magic method:
另一种方法是使用__set_state()
魔术方法:
$object = stdClass::__set_state (array (
'height' => -10924,
'color' => 'purple',
'happy' => false,
'video-yt' => 'AgcnU74Ld8Q'
));
Some more on the __set_state() method, where is it coming from and how is it supposed to be used.
回答by Dave Lampert
Although casting as an (object) works fine on a single hierarchical level, it doesn't go deep. In other words, if we want objects at every level, we'd have to do something like:
尽管作为(对象)的转换在单个层次级别上工作正常,但它并没有深入。换句话说,如果我们想要每个级别的对象,我们必须这样做:
$foods = (object)[
"fruits" => (object)["apple" => 1, "banana" => 2, "cherry" => 3],
"vegetables" => (object)["asparagus" => 4, "broccoli" => 5, "carrot" => 6]
];
However, instead of doing multiple casting as objects, we can wrap the whole thing in a json_encode and json_decode like this:
但是,我们可以将整个内容包装在 json_encode 和 json_decode 中,而不是将其作为对象进行多次转换,如下所示:
$foods = json_decode(json_encode([
"fruits" => ["apple" => 1, "banana" => 2, "cherry" => 3],
"vegetables" => ["asparagus" => 4, "broccoli" => 5, "carrot" => 6]
]));
That makes sure it's an object at the deepest level.
这确保它是最深层次的对象。
To answer klewis, you can then access this like:
要回答 klewis,您可以像这样访问:
echo $foods->vegetables->broccoli;
This example would output the number 5.
此示例将输出数字 5。
回答by Reza Baradaran Gazorisangi
My way of JavaScript-style object literals in PHPis as follows:
我在 PHP中使用 JavaScript 风格的对象字面量的方式如下:
First I create an associative array like this:
首先,我创建一个像这样的关联数组:
$test = array(
'name' => "test",
'exists' => true
);
Then I easily make it an object like this:
然后我很容易地把它变成一个这样的对象:
$test = (object)$test;
Now you can test it:
现在你可以测试它:
echo gettype($test); // "object"
echo $test->name; // "test"
回答by Rob Bennet
If you're wanting to define modules in the object literal pattern "like JavaScript", you could do something like this:
如果你想在“像 JavaScript”这样的对象文字模式中定义模块,你可以这样做:
$object = (object) [
'config' => (object) [
'username' => 'Rob Bennet',
'email' => '[email protected]'
],
'hello' => function() use(&$object) {
return "Hello " . $object->config->username . ". ";
},
'emailDisplay' => function() use(&$object) {
return "Your email address is " . $object->config->email;
},
'init' => function($options) use(&$object) {
$object->config = $options;
$doUsername = $object->hello;
$doEmail = $object->emailDisplay;
return $doUsername() . $doEmail();
}
];
$sayMyInfo = $object->init;
echo $sayMyInfo((object) [
'username' => 'Logan',
'email' => '[email protected]'
]);
In this type of modular scenario, I usually opt for the facade pattern, I just like writing my calls thusly:
在这种类型的模块化场景中,我通常选择外观模式,我只是喜欢这样编写我的调用:
Module::action()->item;
or
或者
Post::get()->title;
Neither of these patterns make it easy (or even possible sometimes) for testing. But this is just proof of concept. Technically, "no" there is no Object Literal in PHP, but if you're used to JavaScript syntax (which I am more so than PHP), you can fake it and do this. As you can see, it's a lot messier in PHP than in JavaScript.
这些模式都不能让测试变得容易(甚至有时可能)。但这只是概念的证明。从技术上讲,“不”在 PHP 中没有 Object Literal,但是如果您习惯了 JavaScript 语法(我比 PHP 更习惯),您可以伪造它并执行此操作。如您所见,在 PHP 中它比在 JavaScript 中要混乱得多。
回答by pgampe
In PHP, you have ro create an instance before you can use a class. Of course you can put the instances into an array later.
在 PHP 中,您必须先创建一个实例,然后才能使用类。当然,您可以稍后将实例放入数组中。
回答by biziclop
If the json_decode(json_encode( $array ))
isn't good for you, then you can use some similar functions like these. Which one is faster, I don't know.
如果json_decode(json_encode( $array ))
不适合你,那么你可以使用一些类似的功能。哪个更快,我不知道。
function deep_cast_object( $o ){
return deep_cast_object_ref( $o );
}
function deep_cast_object_ref( & $o ){
if( is_array( $o ))
$o = (object)$o;
if( is_object( $o ))
foreach( $o as & $v )
deep_cast_object_ref( $v );
return $o;
}
$obj = deep_cast_object(array(
'Fractal' => array(
'of' => array(
'bad' => 'design',
),
),
));
var_dump( $obj );