(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
is_callable — Determina si un valor puede ser llamado como una función en el ámbito actual
$value, bool $syntax_only = false , string &$callable_name = null ): bool
Verifica que value es un callable ,
o que puede ser llamado utilizando la función
call_user_func() .
valueEl valor a verificar.
syntax_only
Si el argumento syntax_only vale true , la
función solo verificará si value puede ser
una función o un método. Rechazará todos los valores
que no sean objetos invocables,
Closure , string s, o array s que no tengan
una estructura válida para ser utilizados como un callback. Un array invocable válido
contiene 2 entradas: la primera debe ser un objeto
o un string, y la segunda un string.
callable_name
Recibe el "nombre de la función invocable", por ejemplo
"SomeClass::someMethod". Tenga en cuenta, sin embargo, que,
a pesar de la implicación de que SomeClass::someMethod()
es un método estático invocable, no es el caso.
Retorna true si value puede ser llamado como
una función, false en caso contrario.
Ejemplo #1 Verificación si un string puede ser llamado como una función
<?php
function someFunction() {}
$functionVariable = 'someFunction';
var_dump(is_callable($functionVariable, false, $callable_name));
var_dump($callable_name);
?>El ejemplo anterior mostrará:
bool(true) string(12) "someFunction"
Ejemplo #2 Verificación si un array puede ser llamado como una función
<?php
class someClass
{
public function someMethod() {}
}
$anObject = new SomeClass();
$methodVariable = [$anObject, 'someMethod'];
var_dump(is_callable($methodVariable, true, $callable_name));
var_dump($callable_name);
?>El ejemplo anterior mostrará:
bool(true) string(21) "SomeClass::someMethod"
Ejemplo #3 is_callable() y los constructores
A pesar de que los constructores son los métodos que se llaman cuando un objeto es creado,
no son métodos estáticos y
is_callable() retornará false para ellos. No es
posible utilizar is_callable() para verificar si una clase puede
ser instanciada desde el ámbito actual.
<?php
class Foo
{
public function __construct() {}
public function foo() {}
}
var_dump(
is_callable(['Foo', '__construct']),
is_callable(['Foo', 'foo'])
);
$foo = new Foo();
var_dump(is_callable([$foo, '__construct']));
?>El ejemplo anterior mostrará:
bool(false) bool(false) bool(true)
true para cualquier método en ese objeto, incluso si
el método no está definido.
If the target class has __call() magic function implemented, then is_callable will ALWAYS return TRUE for whatever method you call it.
is_callable does not evaluate your internal logic inside __call() implementation (and this is for good).
Therefore every method name is callable for such classes.
Hence it is WRONG to say (as someone said):
...is_callable will correctly determine the existence of methods made with __call...
Example:
<?php
class TestCallable
{
public function testing()
{
return "I am called.";
}
public function __call($name, $args)
{
if($name == 'testingOther')
{
return call_user_func_array(array($this, 'testing'), $args);
}
}
}
$t = new TestCallable();
echo $t->testing(); // Output: I am called.
echo $t->testingOther(); // Output: I am called.
echo $t->working(); // Output: (null)
echo is_callable(array($t, 'testing')); // Output: TRUE
echo is_callable(array($t, 'testingOther')); // Output: TRUE
echo is_callable(array($t, 'working')); // Output: TRUE, expected: FALSE
?>Note that -- as mentioned in the migration guide-- starting from PHP 8.0, is_callable() will not work with non-static methods if you use a class name, instead an object of the class should be provided:
<?php
class Test
{
public function method1() { }
public static function method2() { }
}
// Pre PHP 8
var_dump(is_callable(array('Test', 'method1'))); // bool(true)
var_dump(is_callable(array('Test', 'method2'))); // bool(true)
// Post PHP 8
var_dump(is_callable(array('Test', 'method1'))); // bool(false)
var_dump(is_callable(array('Test', 'method2'))); // bool(true)
var_dump(is_callable(array(new Test, 'method1'))); // bool(true)
?>