如何比较两个可调用类型以检查它们是否相等或相同?

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');

非常感谢你

最佳答案

您可以使用 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]);
}

关于php - 如何比较php可调用类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24034206/

10-12 07:16