如何在对象数组中访问属性,而无需在 php 中遍历所有对象


How to access a property in array of objects without looping through all of them in php?

是否可以访问所有对象都具有的对象数组中的属性?假设我有

array(
  [0] => {
    [id] = 5,
    [name] = 'Name'
    [everyobjecthasme] = sameforall
  }, 
  [1] = >{
    [id] = 6
    [name] = 'Name2'
    [everyobjecthasme] = sameforall
  }
)

是否可以访问此对象数组中的属性everyobjecthasme(对所有对象都是通用的),而无需循环,因为我只需要一个对象即可在php中获取此属性?

假设你的对象都有属性'everyobjecthasme',你可以做这样的事情:

$obj1 = new stdClass;
$obj1->everyobjecthasme = 'sameforall';
$obj2 = new stdClass;
$obj2->everyobjecthasme = 'sameforall';
// add objects to array
$array = array(
    0=>$obj1,
    1=>$obj2,
);
// access first object's property
echo $array[0]->everyobjecthasme;