Simple objects in a PHP question [newbie]

I know you can create an array like this:

$a = array();

and add new name value pairs to it, for example:

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

You can even omit the first line, although bad practice!

I find objects easier to read and understand, so I made an array of name arrays and passed it to the object:

$a = (object)$a;

This way I can access the options:

$a->test;

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

thank

+3
source share
4 answers

Yes, the class is stdClassdesigned for just that.

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

, JavaScript:

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

, PHP, JSON, json_decode() stdClass .

+7

stdClass:

$a = new stdClass();
+4

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

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

You can use stdClass for this .

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

Source: https://habr.com/ru/post/1778084/


All Articles