The documentation is a little confusing, and with the recent OO changes it adds a little more to the confusion.
I was curious whether you could pass an object through the user func, modify it in that callback and have the actual object updated or whether some cloning was going on behind the scenes.
<?php
class Test
{
var $sValue = 'abc';
function testing($objTest)
{
$objTest->sValue = '123';
}
}
$obj = new Test();
call_user_func(array($obj, 'testing'), $obj);
var_dump($obj);
?>
This works as expected: The object is not cloned, and $sValue is properly set to '123'. With the OO changes in PHP 5, you don't need to do "function testing(&$objTest)" as it is already passed by reference.
Псевдо-типы, используемые в этой документации
mixed
mixed говорит о том, что параметр может принимать множество (но не обязательно все) типов.
gettype(), например, принимает все типы PHP, тогда как str_replace() принимает строки и массивы.
callback
Некоторые функции, такие как call_user_func() или usort() принимают в качестве параметра определенные пользователем callback-функции. Callback-функции могут быть не только простыми функциями, но также методами объектов, включая статические методы классов.
PHP-функция передается просто как строка ее имени. Вы можете передать любую встроенную или определенную пользователем функцию за исключением array(), echo(), empty(), eval(), exit(), isset(), list(), print() и unset().
Метод созданного объекта передается как массив, содержащий объект в элементе с индексом 0 и имя метода в элементе с индексом 1.
Методы статических классов также могут быть переданы без создания экземпляра объекта передачей имени класса вместо имени объекта в элементе с индексом 0.
Пример #1 Примеры callback-функций
<?php
// простой пример callback
function my_callback_function() {
echo 'hello world!';
}
call_user_func('my_callback_function');
// примеры callback-метода
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}
// вызов метода статического класса без создания объекта
call_user_func(array('MyClass', 'myCallbackMethod'));
// вызов метода объекта
$obj = new MyClass();
call_user_func(array(&$obj, 'myCallbackMethod'));
?>
Pseudo-types and variables used in this documentation
29-Aug-2009 04:20
12-Jun-2009 12:44
I noticed two important thing about putting callbacks into an arg list when calling a function:
1. The function to which the callback refers must be defined earlier in the source stream. So for example:
function main() {...; usort($array, 'sortfunction'); ... }
function sortfunction($a, $b){ return 0; }
Will NOT work, but this will:
function sortfunction($a, $b){ return 0; }
function main() {...; usort($array, 'sortfunction'); ... }
2. It's not really just a string. For example, this doesn't work:
usort($array, ($reverse?'reversesorter':'forwardsorter'));
I found these two discoveries quite counterintuitive.
20-Apr-2009 10:19
An example with PHP 5.3 and lambda functions
<?php
array_map (function ($value) {
return new MyFormElement ($value);
}, $_POST);
?>
24-May-2007 05: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.
08-Feb-2007 10: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');
?>
01-Feb-2007 10: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