Da PHP doch sehr limitiert ist und anscheinend auch nicht viel Wert auf Sicherheit in Bezug auf Zugriffskontrolle legt, muss natürlich auch ne Funktion dafür her.
Code:
// Checks if a particular value (needle) is present in an array (haystack).
// Calls the specified object function (needle_method) dynamically in order to query object attributes via getters
function in_array_method($needle, $needle_method, $haystack, $strict = false)
{
if ($strict)
{
foreach ($haystack as $item)
{
$value = $item->{$needle_method}();
if (isset($value) && $value === $needle)
return true;
}
}
else
{
foreach ($haystack as $item)
{
$value = $item->{$needle_method}();
if (isset($value) && $value == $needle)
return true;
}
}
return false;
}
Meine Funktion basiert auf der Version von Lea Hayes (

), die aber nur auf Attribute mit public modifier zugreifen kann.
Code:
class Testclass
{
public function __construct($id)
{
$this->_ID = $id;
}
public function GetID() { return $this->_ID; }
private $_ID;
}
Durch den
private modifier ist ein Zugriff auch über die in_array Funktion nicht möglich, daher muss ein getter (in diesem Fall
GetID()) spezifiziert werden, damit die Funktion auch darauf zugreifen kann.
Code:
$testarr = array(new Testclass(5), new Testclass(6));
Code:
in_array_method("6", "GetID", $testarr); // true
in_array_method("5", "GetID", $testarr); // true
in_array_method("7", "GetID", $testarr); // false