0

Is it possible to add elements to stdclasses like we do for arrays?

Array (
  [0] => item 1
  [1] => item 2
)

Stdclass (
  [0] => item 1
  [1] => item 2
)

Is it generally harder to manipulate objects as compared to arrays? Since we have lots of array functions to make use of etc.

resting
  • 14,167
  • 16
  • 55
  • 82

4 Answers4

2

Sure, you can add new elements...

$Object = new StdClass();
$Object->item1 = 1;
$Object->item2 = 2;

If you want to iterate object as array you should use PHP SPL ArrayIterator or RecursiveArrayIterator.

Also you can use typecasting to move from array to object and back...

$array = array('item1', 'item2');
$Object = (object)$array;
var_dump($object);
$array = (array)$Object;
var_dump($array);
Kirzilla
  • 15,710
  • 24
  • 81
  • 126
0

Yes, but not numerically indexed.

  $a = new stdclass();
  $a->foo = 'item 1';
  $a->bar = 'item 2';
  $a->goobar = array('item1', 'item2');
  var_dump($a);

If you want more complex scenarios, look at ArrayAccess and ArrayObject.

StasM
  • 10,095
  • 5
  • 53
  • 101
0

Well, the documentation states:

Created by typecasting to object.

As such, you can cast back and forth between (array) and (object) to work stdClass instances with array functions.

demonkoryu
  • 1,225
  • 10
  • 25
0

It's no harder to manipulate. All I would say is things like count and array_search don't work on an object.

Array and objects both have their benefits it depends on what you are trying to achieve.

http://php.net documentation will state what data types can be passed to what functions.

Mike
  • 15,250
  • 2
  • 16
  • 25