问题
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.
回答1:
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);
回答2:
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.
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/4497221/how-can-we-manipulate-std-class-in-php