从php中数组内的对象获取成员值


get member value from object inside array in php

似乎找不到这个问题的答案:如何从对象数组中获得特定值(成员值)?

我的代码很简单:

$people = array();
class Person {
    public $id;
    public $name;
    public $family_name;
    public $dob;
    public $image;
    public function __construct($id, $name, $family_name, $dob, $image){
        $this->$id = (string) $id;
        $this->$name = (string) $name;
        $this->$family_name = (string) $family_name;
        $this->$dob = (string) $dob;
        $this->$image = (string) $image;
    }
    public function get_id(){
        return $this->id;
    }
}
for ($i=0;$i<$no_clients;$i++)
{
    array_push($people, new Person($_SESSION['user_clients'][$i]['client_id'], $_SESSION['user_clients'][$i]['client_name'], $_SESSION['user_clients'][$i]['client_family_name'], $_SESSION['user_clients'][$i]['client_dob'], ROOT_URL.$_SESSION['user_clients'][$i]['client_img']));
}

现在我想从人员数组中获取其中一个人的id

$error = $people[$i]->get_id(); //doesn't seem to work
//not getting a value back even though the session variable is correct

正如你可能已经看到的,我是一个PHP新手,所以任何建议都会很棒。

感谢

您的构造函数错误(属性前面没有$符号)

   $people = array();
    class Person {
        public $id;
        public $name;
        public $family_name;
        public $dob;
        public $image;
        public function __construct($id, $name, $family_name, $dob, $image){
            $this->id = (string) $id;
            $this->name = (string) $name;
            $this->family_name = (string) $family_name;
            $this->dob = (string) $dob;
            $this->image = (string) $image;
        }
        public function get_id(){
            return $this->id;
        }
    }
    for ($i=0;$i<$no_clients;$i++)
    {
        $p=new Person($_SESSION['user_clients'][$i]['client_id'],       $_SESSION['user_clients'][$i]['client_name'], 
$_SESSION['user_clients'][$i]['client_family_name'], 
$_SESSION['user_clients'][$i]['client_dob'], 
ROOT_URL.$_SESSION['user_clients'][$i]['client_img']);
       //print_r($p); //--> check your object
        array_push($people, $p);
    }

//print_r($people);

Array ( [0] => Person Object ( [id] => 1 [name] => M [family_name] => C [dob] => 2011-07-21 [image] => image/1_margaret.jpg ) )

编辑:

重置$i计数器,因为它的最后一个值可能是1。更好地使用foreach循环:

foreach ($people as $person){
    echo $person->get_id();
    }

您的构造函数代码不正确,您错误地引用了属性。删除属性名称开头的$。

例如更改

$this->$id = $id

$this->id = $id