Manipulação de tipos> <NULL
Last updated: Fri, 02 Jan 2009

Pseudo-tipos e variáveis utilizados nesta documentação

mixed

mixed indica que um parâmetro pode aceitar vários (mas não necessariamente todos) os tipos

gettype(), por exemplo, aceita todos os tipos do PHP, enquanto str_replace() somente aceita strings e arrays.

number

number indica que um parâmetro pode ser tanto um integer ou float.

callback

Algumas funções como call_user_func() ou usort() aceitam callback de funções definidas por usuário como parâmetro. Funções de callback não podem ser somente simples funções, mas também métodos de objetos incluindo métodos estáticos de classes.

Uma função PHP é simplesmente passado pelo seu nome como uma string. Você pode passar qualquer função nativa ou definida por usuário. Note que construtores da linguagem como array(), echo(), empty(), eval(), exit(), isset(), list(), print() ou unset() não podem ser chamados usando um callback.

A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.

Apart from common user-defined function, create_function() can be used to create an anonymous callback function.

Exemplo #1 Exemplo de funções callback

<?php

// Exemplo simples de callback
function my_callback_function() {
    echo 
'Olá Mundo!';
}
call_user_func('my_callback_function');

// Exemplo de método callback
class MyClass {
    static function 
myCallbackMethod() {
        echo 
'Olá Mundo!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function'); 

// Type 2: Static class method call
call_user_func(array('MyClass''myCallbackMethod'));

// Type 3: Chamada de método de objeto
$obj = new MyClass();
call_user_func(array(&$obj'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class {
    public static function 
who() {
        echo 
"A\n";
    }
}

class 
extends {
    public static function 
who() {
        echo 
"B\n";
    }
}

call_user_func(array('B''parent::who')); // A

?>

Nota: No PHP 4, vocÊ irá ter que usar a referência para criar um callback que aponta para o objeto atual, e não uma cópia dele. Para mais detalhes, veja Referências explicadas.

void

void no tipo de retorno indica que não há valor a ser retornado. void na lista de parâmetros indica que a função não aceita parâmetros.

...

$... no protótipo de uma função significa e assim por diante. O nome desta variável é usado quando a função suporta infinito número de argumentos.



Manipulação de tipos> <NULL
Last updated: Fri, 02 Jan 2009
 
User Contributed Notes
Pseudo-tipos e variáveis utilizados nesta documentação
Hayley Watson
24-May-2007 02:44
The mixed pseudotype is explained as meaning "multiple but not necessarily all" types, and the example of str_replace(mixed, mixed, mixed) is given where "mixed" means "string or array".
Keep in mind that this refers to the types of the function's arguments _after_ any type juggling.
levi at alliancesoftware dot com dot au
08-Feb-2007 08:44
Parent methods for callbacks should be called 'parent::method', so if you wish to call a non-static parent method via a callback, you should use a callback of
<?
 
// always works
 
$callback = array($this, 'parent::method')

 
// works but gives an error in PHP5 with E_STRICT if the parent method is not static
 
$callback array('parent', 'method');
?>
Edward
01-Feb-2007 08:15
To recap mr dot lilov at gmail dot com's comment: If you want to pass a function as an argument to another function, for example "array_map", do this:

regular functions:
<?
array_map
(intval, $array)
?>

static functions in a class:
<?
array_map
(array('MyClass', 'MyFunction'), $array)
?>

functions from an object:
<?
array_map
(array($this, 'MyFunction'), $array)
?>

I hope this clarifies things a little bit

Manipulação de tipos> <NULL
Last updated: Fri, 02 Jan 2009