How to compare types called by php?

How to compare two called 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');

Many thanks

+4
source share
1 answer

You can use the third parameter is_callable to get the called name , which is a string.

If the called is array('MyClass', 'myCallbackMethod'), then the called 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]); 
}
+6
source

Source: https://habr.com/ru/post/1543188/


All Articles