如何比较php可调用类型?

时间:2014-06-04 09:50:41

标签: php

如何比较两种可调用类型以检查它们是相同还是相同?

function addCallable(callable $cb)
{
    if(/*already exists*/)
        throw new Exception("Callable was already added to the collection");
    else
        $this->collection[] = $cb;
}

function removeCallable(callable $cb)
{
    $key = array_search(/* ??? */);
    unset($this->collection[$key]);
}

$this->addCallable(array('MyClass', 'myCallbackMethod'));
try{ $this->addCallable('MyClass::myCallbackMethod'); }catch(Exception $e){}
$this->removeCallable('MyClass::myCallbackMethod');

非常感谢

1 个答案:

答案 0 :(得分:7)

您可以使用 is_callable 函数的第三个参数来获取可调用名称,这是一个字符串。

如果可调用者为array('MyClass', 'myCallbackMethod'),则可调用名称为'MyClass::myCallbackMethod'

function addCallable(callable $cb)
{
    is_callable($cb, true, $callable_name);

    if(isset($this->collection[$callable_name])) {
        throw new Exception("Callable was already added to the collection");
    } else {
        $this->collection[$callable_name] = $cb;
    }          
}

function removeCallable(callable $cb)
{
    is_callable($cb, true, $callable_name);
    unset($this->collection[$callable_nam]); 
}