Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

Does PHP feature short hand syntax for objects?

In javascript you can easily create objects and Arrays like so:

var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];

Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?

$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
                                      'bar'=>2);

So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays?

question from:https://stackoverflow.com/questions/455800/does-php-feature-short-hand-syntax-for-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For simple objects, you can use the associative array syntax and casting to get an object:

<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"

But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...