is_callable()
This function is a good check when using call_user_func() for example. It lets you know if the variable is holding a valid function name.
By default it will check that the function exists and you can actually call it from the scope you’re in. Set the second parameter to true and it will only check if the syntax is valid.
And as with other functions that allow you to call functions dynamically, class functions are noted as an array: the class name (or instance), and the method name.
$func = 'monkey'; $class = 'Banana'; $x = is_callable( $func ); // false $y = is_callable( $func, true ); // true $x = is_callable( array( $class, $func ) ); // false $y = is_callable( array( $class, $func ), true ); // true
Those examples returned true when we checked syntax only. That’s because there were no functions defined. Here we’ll look at what happens when there are functions defined.
$func = 'monkey'; $class = 'Banana'; $x = is_callable( $func ); // false $y = is_callable( 'monkey2' ); // true $x = is_callable( array( $class, $func ) ); // true $y = is_callable( array( $class, 'monkey2' ) ); // false class Banana { static public function monkey() { echo 'hi'; } private function monkey2() { echo 'what?'; } } function monkey2() { echo 'bye'; }
