[英]Iterate over object properties and omit certain ones
我正在嘗試找出迭代對象屬性的最佳方法,以便為插入或更新構建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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.