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

时间:2012-08-26 13:49:37

标签: php arrays object

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

我的代码非常简单:

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

现在我想从人员阵列中获取其中一个人的身份

$error = $people[$i]->get_id(); //doesn't seem to work
//not getting a value back even though the session variable is correct
你可能已经看过,我是一个PHP新手,所以任何建议都会很棒。

由于

2 个答案:

答案 0 :(得分: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($人);

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();
    }

答案 1 :(得分:2)

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

例如改变

$this->$id = $id

$this->id = $id