迭代对象属性并省略某些属性

时间:2016-01-09 13:08:32

标签: php

我试图找出迭代对象属性的最佳方法,这样我就可以为插入或更新构建一个sql查询。我也希望能够省略迭代中的某些字段。

下面是一个示例对象,我想获取名称和年龄,但省略雇主,因为这是来自另一个表的连接。

class person
{
     private $_name, $_age, $_employer;

     public function get_name()
     {
          return $this->_name;
     }
     public function get_age()
     {
          return $this->_age;
     }
     public function get_employer()
     {
          return $this->_employer;
     }
}

我可以将一个对象转换为数组以获取属性,但我仍然没有很好的方法来省略某些属性。

$personObj = new person();
foreach((array)$personObj as $k => $v)
{
     $sql .= "...";
}

1 个答案:

答案 0 :(得分:3)

希望这会给你一个提示

class person
{
     private $_name = 'dude';
     private $_age = '27';
     private $_employer = 'yes';

     public function get_name()
     {
          return $this->_name;


     }
     public function get_age()
     {
          return $this->_age;
     }

     public function get_employer()
     {
          return $this->_employer;
     }
}

$person = new person();
$required = array('name','age');
foreach($required as $req)
{
    $func = "get_{$req}";
    echo $person->$func();
}

https://3v4l.org/vLdAN

相关问题