2014-10-03 139 views
0

methosHere是调用我创建的类:PHP:呼叫的方法动态

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 

我认为这是动态调用属性的方式..我该怎么办错了?

谢谢

+0

由于'getId'是一种方法,而不是一个道具,你要称呼其为方法:'$ object - > $ getter();' – hindmost 2014-10-03 12:48:52

+0

缺少括号():) – pietro 2014-10-03 12:49:04

回答

3

试试这个方法:

的第一个元素是对象,第二个是方法。

call_user_func(array($object, $getter)) 

你也可以不用call_user_func

$object->{$getter}(); 

或者:

$object->$getter(); 
2

您尝试调用类属性,它是在private范围。

您为此属性创建了一个getter方法(Role::getId())。现在你必须调用该方法,而不是属性本身(它是私有的,不能在包含它的Role类实例之外访问)。

所以,你必须使用call_user_func()

$id = call_user_func(array($object, $getter)); 
+0

'call_user_function'无法帮助访问私有方法,除非它在该对象内调用。 – hindmost 2014-10-03 12:50:53

+0

有一个公共方法'Role :: getId()',它可以由'call_user_func()'调用。 – TiMESPLiNTER 2014-10-03 12:51:57