Simple Objects in PHP question

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 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

Answers


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.


Need Your Help

What exactly happens when an OS goes into kernel mode?

operating-system kernel

I find that neither my textbooks or my googling skills give me a proper answer to this question. I know it depends on the operating system, but on a general note: what happens and why?

Best way to update some fields of a detached object on Hibernate?

java hibernate orm

I was wondering what's the best way to update some fields of a dettached object using HB on Java. Specially when the object has child objects attributes. For Example (annotations removed and fields

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.