methosHere是对我创建的类的调用:
Utils::search($idRole, $this->roles, 'getId');在Utils中,搜索方法:
public static function search ($needle, $haystack, $getter) {
$found = false;
$i = 0;
while($i < count($haystack) || $found) {
$object = $haystack[$i];
if($object->$getter === $needle) {
$found = true;
}
}
return $found;
}干草堆是一个角色对象数组。以下是角色类的一部分:
class Role
{
private $id;
private $nom;
public function __construct($id = 0, $nom = null) {
$this->id = $id;
$this->nom = $nom;
}
public function getId()
{
return $this->id;
}
}运行$object->$getter部件我有一个异常:
Undefined property: Role::$getId我认为这是动态调用属性的方法。我做错什么了?
谢谢
发布于 2014-10-03 12:52:26
试着这样做:
第一个元素是对象,第二个元素是方法。
call_user_func(array($object, $getter))您也可以不使用call_user_func来完成它。
$object->{$getter}();或者:
$object->$getter();发布于 2014-10-03 12:48:51
您尝试调用private作用域中的类属性。
您为该属性(Role::getId())创建了一个getter方法。现在,您必须调用该方法,而不是属性本身(该属性是私有的,不能在持有该方法的角色类实例之外访问)。
所以你必须使用call_user_func()
$id = call_user_func(array($object, $getter));https://stackoverflow.com/questions/26179143
复制相似问题