您可以在過濾器數組上使用array_reduce()來測試對象的各個屬性,從而將它們減少爲單個布爾值。像
class myObject {
public $name;
public $isAnimal;
public $isMammal;
public $hasFur;
public function __construct($name, $isAnimal = false, $isMammal = false, $hasFur = false) {
$this->name = $name;
$this->isAnimal = $isAnimal;
$this->isMammal = $isMammal;
$this->hasFur = $hasFur;
}
}
$table = new myObject('Table');
$dolphin = new myObject('Dolphin', true, true);
$dog = new myObject('Dog', true, true, true);
$objectSet = [
$table,
$dolphin,
$dog,
];
$filters = array('isAnimal', 'hasFur');
foreach($objectSet as $objectValue) {
var_dump(
$objectValue->name,
array_reduce(
$filters,
function($returnValue, $filter) use ($objectValue) {
$returnValue &= $objectValue->{$filter};
return (bool) $returnValue;
},
true
)
);
}
Demo
如果你寫了一個合適的函數,它就會成爲一個班輪。 –
已經寫了,只是好奇,如果有一個性感的PHP技巧,看起來更好,通過合併數組或其他東西 – NaturalBornCamper