PHP 8.3.4 Released!

is_callable

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

is_callable Verifica se um valor pode ser chamado como uma função a partir do escopo atual.

Descrição

is_callable(mixed $value, bool $syntax_only = false, string &$callable_name = null): bool

Verifica se um valor é do tipo callable.

Parâmetros

value

O valor a ser verificado

syntax_only

Se definido para true a função apenas verifica se value pode ser uma função o método. Ela irá apenas rejeitar variáveis simples que não sejam strings, ou um array que não tem estrutura válida para ser usado como função de chamada de retorno. Os válidos devem ter apenas 2 entradas, a primeira delas é um objeto ou uma string, e a segunda uma string.

callable_name

Recebe o "nome da função chamável". No exemplo abaixo é "someClass::someMethod". Note, entretando, que embora a implicação de que someClass::SomeMethod() seja um método estático que pode ser chamado, este não é o caso.

Valor Retornado

Retorna true se value puder ser chamado como função, false caso contrário.

Exemplos

Exemplo #1 Exemplo de is_callable()

<?php
// Como verificar uma variável para ver se ela pode ser chamada
// como uma função.

//
// Variável simples contendo uma função
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name)); // bool(true)

echo $callable_name, "\n"; // someFunction

//
// Array contendo um método
//

class someClass {

function
someMethod()
{
}

}

$anObject = new someClass();

$methodVariable = array($anObject, 'someMethod');

var_dump(is_callable($methodVariable, true, $callable_name)); // bool(true)

echo $callable_name, "\n"; // someClass::someMethod

?>

Exemplo #2 Exemplo de is_callable() e contrutores

is_callable() reporta construtores como métodos que não podem ser chamados.

<?php

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

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

O exemplo acima produzirá:

bool(false)
bool(false)

Notas

  • Um objeto é sempre chamável se ele implementar o método __invoke(), e este método estiver visível no escopo atual.
  • Um nome de classe é chamável se ela implementa o método __callStatic().
  • Se um objeto implementa o método __call(), então esta função retornará true para qualquer método neste objeto, mesmo se o método não estiver definido.
  • Esta função pode disparar o auto-carregamento se chamada com o nome de uma classe.

Veja Também

add a note

User Contributed Notes 2 notes

up
34
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
17
mohamed dot elidrissi at protonmail dot com
2 years ago
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)

?>
To Top