Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare php's callable types?

Tags:

php

How do I compare two callable types to check if they are equal or the same?

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

thank you very much

like image 605
sveva Avatar asked Feb 13 '23 19:02

sveva


1 Answers

You could use the third parameter of is_callable function to get the callable name, which is a string.

If the callable is array('MyClass', 'myCallbackMethod'), then the callable name will be '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]); 
}
like image 74
xdazz Avatar answered Feb 15 '23 10:02

xdazz