Php 迭代对象属性并忽略某些属性

Php 迭代对象属性并忽略某些属性,php,Php,我试图找出迭代对象属性的最佳方法,以便为插入或更新构建sql查询。我还希望能够在迭代中省略某些字段 下面是一个示例对象,我想获取名称和年龄,但忽略雇主,因为这是另一个表的联接 class person { private $_name, $_age, $_employer; public function get_name() { return $this->_name; } public function get_a

我试图找出迭代对象属性的最佳方法,以便为插入或更新构建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 .= "...";
}

希望这能给你一个提示

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

希望这能给你一个提示

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

您想从类内部还是外部获取值?你也试过一些东西来达到你的目标吗?我试着在课堂之外获得价值观。我不确定开始时的最佳方法。您想从类内部还是外部获取值?你也试过一些东西来达到你的目标吗?我试着在课堂之外获得价值观。我不确定最好的开始方式。谢谢你的例子。这绝对有助于给我指引方向。老兄,节省了我的时间,+1感谢这个例子。这绝对有助于给我指引方向。哥们,节省了我的时间,+1