开发者

Simple Objects in PHP question [newbie]

I know you can create an array like this:

$a = array();

and append new name value pairs to it like thus:

$a['test'] = 'my new value';

It开发者_StackOverflow is even possible to omit the first line, although bad practice!

I find objects easier to read and understand, so what I've done is taken the array of name value pairs and cast it into an object:

$a = (object)$a;

Thus I can access the parameters:

$a->test;

It seems wasteful for the extra overhead of creating an Array to start with, is it possible to simply create an object and then somehow just add the name value pairs to it in a similar way as I would do the array?

Thanks


Yes, the stdClass class is designed for just that.

$a = new stdClass;
$a->test = 'my new value';

You can think of it as being akin to the following JavaScript code:

var a = {};
a.test = 'my new value';

In fact, if you had some PHP code that received data as JSON, running json_decode() on the data results in a stdClass object with the included properties.


You can use the stdClass object for that:

$a = new stdClass();


It is very simple even without stdclass. You can simply do

class obj{}
$obj = new obj;
$obj->foo = 'bar';


You can use stdClass for this.

$object = new StdClass;  
$object->foo = 'bar';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜