1

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

我的代码很简单:

$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']));
}

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

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

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

谢谢

4

2 回答 2

3

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

   $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();
    }
于 2012-08-26T13:55:30.267 回答
2

Your constructor code is not correct, you're incorrectly referencing your properties. Remove the $ from the start of the property names.

Eg change

$this->$id = $id

to

$this->id = $id
于 2012-08-26T13:57:28.987 回答