Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

oop - Creating anonymous objects in php

As we know, creating anonymous objects in JavaScript is easy, like the code below:

var object = { 
    p : "value", 
    p1 : [ "john", "johnny" ]
};

alert(object.p1[1]);

Output:

an alert is raised with value "johnny"

Can this same technique be applied in PHP? Can we create anonymous objects in PHP?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

"Anonymous" is not the correct terminology when talking about objects. It would be better to say "object of anonymous type", but this does not apply to PHP.

All objects in PHP have a class. The "default" class is stdClass, and you can create objects of it this way:

$obj = new stdClass;
$obj->aProperty = 'value';

You can also take advantage of casting an array to an object for a more convenient syntax:

$obj = (object)array('aProperty' => 'value');
print_r($obj);

However, be advised that casting an array to an object is likely to yield "interesting" results for those array keys that are not valid PHP variable names -- for example, here's an answer of mine that shows what happens when keys begin with digits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...