当值是对象时如何获取数组内容?

时间:2011-06-01 06:49:11

标签: php arrays

我有一个包含不同数据类型的数组。那些是int和object。该数组如下。

Array ( 
  [isHR] => 1 
  [1] => Array ( 
    [0] => MyQuota Object ( 
      [year:private] => 2011 
      [leaveId:private] => L001 
      [employeeId:private] => 
      [NoOfDays:private] => 7.00 
      [leaveName:private] => Casual Leave 
      [Message:private] => 
    ) 
    [1] => MyQuota Object ( 
      [year:private] => 2011 
      [leaveId:private] => LTY002 
      [employeeId:private] => 
      [NoOfDays:private] => 55.00 
      [leaveName:private] => Priviledged Leave
      [Message:private] => 
    ) 
  ) 
  [Length] => 8 
)

这里我需要获取并设置名为“NoOfDays:private”的数组属性。我怎么能得到这个?

3 个答案:

答案 0 :(得分:1)

最简单直接的方法之一,请参阅此页面。 [1] http://php.net/manual/en/function.get-object-vars.php

答案 1 :(得分:1)

您可能无法访问对象的私有属性。要么公开它们,要么定义getter和setter方法。

访问公共属性:

echo $arr[1][0]->NoOfDays

答案 2 :(得分:1)

添加getter和setter:

class MyQuota
{
    private $year;
    private $leaveId;
    private $employeeId;
    private $NoOfDays;
    private $leaveMessage;
    private $Message;

    /* more code */

    public function getNoOfDays()
    {
        return $this->NoOfDays;
    }

    public function setNoOfDays($noOfDays)
    {
        $this->NoOfDays = $noOfDays;
    }

    /* more getters and setters */

}

并且,使用您的数组,使用它:

$days = $array[0][1]->getNoOfDays();