Принять функцию как параметр в PHP
Мне было интересно, возможно ли или нет передать функцию в качестве параметра в PHP; Я хочу что-то вроде, когда вы программируете в JS:
object.exampleMethod(function(){
// some stuff to execute
});
Я хочу выполнить эту функцию где-нибудь в методе exampleMethod. Возможно ли это в PHP?
Ответы
Ответ 1
Возможно, если вы используете PHP 5.3.0 или выше.
См. Анонимные функции в руководстве.
В вашем случае вы должны определить exampleMethod
следующим образом:
function exampleMethod($anonFunc) {
//execute anonymous function
$anonFunc();
}
Ответ 2
Чтобы добавить к остальным, вы можете передать имя функции:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
Это будет работать на PHP4.
Ответ 3
Вы также можете использовать create_function, чтобы создать функцию как переменную и передать ее. Хотя, мне нравится чувство анонимных функций. Иди зомбат.
Ответ 4
Просто введите код так:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
было бы здорово, если бы вы могли придумать что-то подобное (вдохновленное Laravel Illuminate):
Object::method("param_1", function($param){
$param->something();
});
Ответ 5
Простой пример с использованием класса:
class test {
public function works($other_parameter, $function_as_parameter)
{
return $function_as_parameter($other_parameter) ;
}
}
$obj = new test() ;
echo $obj->works('working well',function($other_parameter){
return $other_parameter;
});
Ответ 6
PHP VERSION >= 5.3.0
Пример 1: базовый
function test($test_param, $my_function) {
return $my_function($test_param);
}
test("param", function($param) {
echo $param;
}); //will echo "param"
Пример 2: объект std
$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
return $my_function($test_param);
};
$test = $obj->test;
$test("param", function($param) {
echo $param;
});
Пример 3: вызов нестатического класса
class obj{
public function test($test_param, $my_function) {
return $my_function($test_param);
}
}
$obj = new obj();
$obj->test("param", function($param) {
echo $param;
});
Пример 4: вызов статического класса
class obj {
public static function test($test_param, $my_function) {
return $my_function($test_param);
}
}
obj::test("param", function($param) {
echo $param;
});
Ответ 7
Протестировано для PHP 5.3
Как я вижу здесь, анонимная функция может вам помочь:
http://php.net/manual/en/functions.anonymous.php
Что вам, возможно, понадобится, и он не сказал перед этим , как передать функцию без ее обертки внутри встроенной функции.
Как вы увидите позже, вам нужно передать имя функции, записанное в строке в качестве параметра, проверить его "вызываемость" и затем вызвать его.
Функция проверки:
if( is_callable( $string_function_name ) ){
/*perform the call*/
}
Затем, чтобы вызвать его, используйте этот фрагмент кода (если вам нужны параметры, поместите их в массив), посмотрите на: http://php.net/manual/en/function.call-user-func.php
call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );
как следует (аналогичным, без параметров):
function funToBeCalled(){
print("----------------------i'm here");
}
function wrapCaller($fun){
if( is_callable($fun)){
print("called");
call_user_func($fun);
}else{
print($fun." not called");
}
}
wrapCaller("funToBeCalled");
wrapCaller("cannot call me");
Здесь класс, объясняющий, как сделать что-то подобное:
<?php
class HolderValuesOrFunctionsAsString{
private $functions = array();
private $vars = array();
function __set($name,$data){
if(is_callable($data))
$this->functions[$name] = $data;
else
$this->vars[$name] = $data;
}
function __get($name){
$t = $this->vars[$name];
if(isset($t))
return $t;
else{
$t = $this->$functions[$name];
if( isset($t))
return $t;
}
}
function __call($method,$args=null){
$fun = $this->functions[$method];
if(isset($fun)){
call_user_func_array($fun,$args);
} else {
// error out
print("ERROR: Funciton not found: ". $method);
}
}
}
?>
и пример использования
<?php
/*create a sample function*/
function sayHello($some = "all"){
?>
<br>hello to <?=$some?><br>
<?php
}
$obj = new HolderValuesOrFunctionsAsString;
/*do the assignement*/
$obj->justPrintSomething = 'sayHello'; /*note that the given
"sayHello" it a string ! */
/*now call it*/
$obj->justPrintSomething(); /*will print: "hello to all" and
a break-line, for html purpose*/
/*if the string assigned is not denoting a defined method
, it treat as a simple value*/
$obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';
echo $obj->justPrintSomething; /*what do you expect to print?
just that string*/
/*N.B.: "justPrintSomething" is treated as a variable now!
as the __set override specify"*/
/*after the assignement, the what is the function destiny assigned before ? It still works, because it held on a different array*/
$obj->justPrintSomething("Jack Sparrow");
/*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/
$obj->justPrintSomething( $obj->justPrintSomething );
/*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/
/*in fact, "justPrintSomething" it a name used to identify both
a value (into the dictionary of values) or a function-name
(into the dictionary of functions)*/
?>
Ответ 8
Согласно ответу @zombat, лучше сначала проверить анонимные функции:
function exampleMethod($anonFunc) {
//execute anonymous function
if (is_callable($anonFunc)) {
$anonFunc();
}
}