Skip to content
Advertisement

PHP function parameter with callable hint… can it be NULL?

I would like to have a PHP function which accepts a parameter A, which I have given the type hint callable. Trouble is in some situations I would like to be able to pass NULL or something like that, as the parameter value, indicating that the call back hasn’t been provided. I get the following error:

"Argument must be callable, NULL given".

Any ideas how I can implement this please?

In response to answers posted and questions…

PHP version is 5.4.14

Code is…

class DB
{
    protected function ExecuteReal($sqlStr, array $replacements, callable $userFunc, $allowSensitiveKeyword)
    {
        ...
        if( $userFunc != NULL && is_callable($userFunc) )
            $returnResult = $call_user_func($userFunc, $currRow);
        ...
    }

    ...
    public function DoSomething(...)
    {
        $result = $this->ExecuteReal($queryStr, Array(), NULL, TRUE);   
        ...
    }
}

In the above code snippet, I don’t need to be called back with any data so instead of passing in a callable object I just pass in NULL. But this is the cause of the error msg.

The solution is answer below… thanks guys 🙂

Advertisement

Answer

When you use type-hinting (only array interfaces, and classes can be type-hinted /till php 5.6/. /since 7.0 it is possible to typehint scalar types as well/), you can set the default value of the parameter to null. If you want to, let the parameter be optional.

$something = 'is_numeric';
$nothing = null;

function myFunction(Callable $c = null){
      //do whatever

}

All works:

 myFunction();
 myFunction($nothing);
 myFunction($something);

Read more here: http://php.net/manual/en/language.oop5.typehinting.php

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement