|
|
mixed говорит о том, что параметр может принимать
множество (но не обязательно все) типов.
gettype(), например, принимает все типы PHP, тогда
как str_replace() принимает строки и массивы.
number говорит о том, что параметр может быть либо
integer, либо float.
Некоторые функции, такие как call_user_func()
или usort() принимают в качестве параметра
определенные пользователем callback-функции. Callback-функции могут
быть не только простыми функциями, но также методами объектов,
включая статические методы классов.
PHP-функция передается просто как строка ее имени. Вы можете передать
любую встроенную или определенную пользователем функцию за
исключением
array(),
echo(),
empty(),
eval(),
exit(),
isset(),
list(),
print() и
unset().
Метод созданного объекта передается как массив, содержащий объект в
элементе с индексом 0 и имя метода в элементе с индексом 1.
Методы статических классов также могут быть переданы без создания
экземпляра объекта передачей имени класса вместо имени объекта в
элементе с индексом 0.
Пример 11-11.
Примеры callback-функций
|
<?php
function my_callback_function() {
echo 'hello world!';
}
call_user_func('my_callback_function');
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}
call_user_func(array('MyClass', 'myCallbackMethod'));
$obj = new MyClass();
call_user_func(array(&$obj, 'myCallbackMethod'));
?>
|
|
add a note
User Contributed Notes
Псевдо-типы, используемые в этой документации
Hayley Watson
23-May-2007 10: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 02: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 02: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
mr dot lilov at gmail dot com
11-Aug-2005 06:17
This's a useful example about callback, Look at the session_set_save_handler function.
From: http://www.zend.com/zend/spotlight/code-gallery-wade8.php
<?php
$ses_class = new session();
session_set_save_handler (array(&$ses_class, '_open'),
array(&$ses_class, '_close'),
array(&$ses_class, '_read'),
array(&$ses_class, '_write'),
array(&$ses_class, '_destroy'),
array(&$ses_class, '_gc'));
session_start();
class session
{
var $ses_table = "sessions";
var $db_con = "Y";
var $db_host = "localhost";
var $db_user = "username";
var $db_pass = "password";
var $db_dbase = "dbname";
function db_connect() {
............
}
function _open($path, $name) {
.............
}
function _close() {
..............
}
function _read($ses_id) {
.................
}
function _write($ses_id, $data) {
...........
}
function _gc($life) {
............
}
}
?>
|