is_callable

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

is_callable Verificar que los contenidos de una variable puedan ser llamados como una función

Descripción

is_callable(mixed $var, bool $syntax_only = false, string &$callable_name = ?): bool

Verifica que los contenidos de una variable puedan ser llamados como una función. Esto permite revisar que los contenidos de una variable contengan el nombre de una función válida, o que un array contenga un objeto adecuadamente codificado y un nombre de función.

Parámetros

var

El valor a revisar

solo_sintaxis

Si es true la función solo verifica que nombre pueda ser una función o un método. Solo rechazará variables simples que no sean cadenas, o un array que no tenga una estructura válida para ser usado como llamada de retorno. Se espera que las matrices válidas tengan solo 2 entradas, la primera de las cuales es un objeto o una cadena, y la segunda una cadena.

callable_name

Recibe el "nombre que puede ser llamado". En el ejemplo siguiente aquél es "algunaClase:algunMetodo". Tenga en cuenta, sin embargo, que a pesar de la implicación de que algunaClase::algunMetodo() es un método estático que puede ser llamado, este no es el caso.

Valores devueltos

Devuelve true si var puede ser llamado, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de is_callable()

<?php
//  Cómo chequear una variable para ver si puede ser llamada
//  como una función.

//
//  Variable simple que contiene una función
//

function algunaFuncion() 
{
}

$variableFuncion 'algunaFuncion';

var_dump(is_callable($variableFuncionfalse$nombre_a_llamar));  // bool(true)

echo $nombre_a_llamar"\n";  // algunaFuncion

//
//  Array que contiene un método
//

class algunaClase {

  function 
algunMetodo() 
  {
  }

}


$unObjeto = new algunaClase();

$variableMetodo = array($unObjeto'algunMetodo');

var_dump(is_callable($variableMetodotrue$nombre_a_llamar));  //  bool(true)

echo $nombre_a_llamar"\n";  //  algunaClase::algunMetodo

?>

Ejemplo #2 Función is_callable() y constructores

A partir de PHP 5.3.0 la función is_callable() reporta constructores como que no se pueden llamar. Esto afecta el estilo de los constructores de PHP 5 (__construct) así también el estilo de los constructors de PHP 4 (por ejemplo metodos con el mismo nombre de la clase). Anteriormente, ambos casos han sido considerados como llamables.

<?php

class Foo
{
    public function 
__construct() {}
    public function 
foo() {}
}

var_dump(
    
is_callable(array('Foo''__construct')),
    
is_callable(array('Foo''foo'))
);

El resultado del ejemplo sería:

bool(false)
bool(false)

Ver también

add a note add a note

User Contributed Notes 5 notes

up
31
izharaazmi at gmail dot com
8 years ago
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
?>
up
2
rahadotaboulfethatgmail.com
16 years ago
is_callable generates an [E_STRICT] error if the  tested method cannot be called staticly. (and returns the good value)

I used @is_called
i'm using php 5.2.1
up
0
jlh
5 years ago
The story about __call() is a bit more complicated unfortunately. It will always return true ONLY if you pass an instance of a class, not if you pass the class name itself:

<?php
class MyClass {
    public function
method() { }
    public function
__call($name, $arguments) { }
}

is_callable([MyClass::class, 'method']); // true
is_callable([new MyClass(), 'method']); // true
is_callable([MyClass::class, 'other']); // false!!!
is_callable([new MyClass(), 'other'])); // true
up
0
fgm at osinet dot fr
12 years ago
Note that, for the purpose of this function, an abstract method, although necessarily non-callable since it does not have a body, is still considered to be callable:

<?php
abstract class Foo {
  abstract function
bar();
}

echo
is_callable(array('Foo', 'bar'));
// display: 1
?>
up
0
Quis strrev TA omicidio strrev TOD com
16 years ago
is_callable() does _not_ check wheter this function is disabled by php.ini's disable_functions

use:

<?PHP
function is_disabled($function) {
 
$disabled_functions=explode(',',ini_get('disable_functions'));
  return
in_array($function, $disabled_functions);
}
?>

I`m running PHP 5.2.4
To Top