James James - 3 months ago 24
PHP Question

PHP is_callable with Type Definitions

Been searching the PHP documentation and this doesn't seem possible but wanted to check.

Say I have a function like this:

class Utils {
static function doSomething( Array $input ){
...
}
}


Is is possible to use a inbuilt PHP function like
is_callable
to check if both the function exists and if the variable I have will be accepted by the type definition in the function.

So:

$varA = array( 'a', 'b', 'c' );
$varB = 'some string';

$functionToCall = array( 'Utils', 'doSomething' );

is_callable( $functionToCall, $varA ) => true;
is_callable( $functionToCall, $varB ) => false;


Of course
is_callable
cannot be used like this. But can it be done without using a Try Catch?

If not would this be the best way around it?

try {
Utils::doSomething( 10 )
} catch (TypeError $e) {
// react here
}


Thanks!

Answer

You can use a ReflectionClass to access the ReflectionMethod

With the ReflectionMethod you can access the ReflectionParameter and check the type or the class of the parameter

try{
    $method = new ReflectionMethod('Utils', 'doSomething');
    if(!$method->isStatic()){
        $methodOk = false;
    }

    foreach($method->getParameters() as $parameter){
        //Choose the appropriate test
        if($parameter->getType() != $varA || !is_a($varA ,$parameter->getClass()->getName())){
            $methodOk = false;
        }
    }
}
catch(ReflectionException $ex){
    $methodOk = false;
}

Reference : reflectionparameter and reflection

Comments