3

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

Elzo Valugi
  • 24,234
  • 13
  • 88
  • 112
user505988
  • 507
  • 1
  • 9
  • 23

4 Answers4

7

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.

Community
  • 1
  • 1
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
4

You can use the stdClass object for that:

$a = new stdClass();
ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
1

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

class obj{}
$obj = new obj;
$obj->foo = 'bar';
Thariama
  • 47,807
  • 11
  • 127
  • 149
  • 1
    Thanks - i thought it probably would be as simple as that! – user505988 Dec 02 '10 at 11:38
  • Uh, you're missing `$obj = new obj;` between the two statements – BoltClock Dec 02 '10 at 11:47
  • 1
    @Thariama: You forgot to create an instance of obj. `$obj = new obj;` Actually the class is futile. It's an implicit extension of stdClass and not adding anything to it. Therefore it's just another entry in types table at runtime and potentially confusing developers. – rik Dec 02 '10 at 11:53
  • @rik: [`obj` does not extend `stdClass`](http://stackoverflow.com/questions/4218693/typehinting-method-should-accept-any-arg-that-is-an-object), not even implicitly. – BoltClock Dec 02 '10 at 12:19
  • @BoltClock: It does. `class obj extends stdClass {}` is semantically the same. Of course you have to use the correct type hints. But that does not mean the classes are different. – rik Dec 02 '10 at 13:08
  • @rik: In that case, why does `class obj {} var_dump(new obj instanceof stdClass);` say `bool(false)`, but `class obj2 extends stdClass {} var_dump(new obj2 instanceof stdClass);` say `bool(true)`? – BoltClock Dec 02 '10 at 13:14
  • 1
    @rik: Fine if you consider two separately classes with identical members *semantically* like, but saying that all classes inherit from `stdClass` is just wrong. A class only inherits from it if you say so in code. It's not a root class. – BoltClock Dec 02 '10 at 13:22
0

You can use stdClass for this.

$object = new StdClass;  
$object->foo = 'bar';
Elzo Valugi
  • 24,234
  • 13
  • 88
  • 112