在 PHP 中接受函数作为参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2700433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accept function as parameter in PHP
提问by Cristian
I've been wondering whether is possible or not to pass a function as parameter in PHP; I want something like when you're programming in JS:
我一直想知道是否可以在 PHP 中将函数作为参数传递;当你用 JS 编程时,我想要这样的东西:
object.exampleMethod(function(){
// some stuff to execute
});
What I want is to execute that function somewhere in exampleMethod. Is that possible in PHP?
我想要的是在exampleMethod中的某处执行该函数。这在 PHP 中可能吗?
回答by zombat
It's possible if you are using PHP 5.3.0 or higher.
如果您使用的是 PHP 5.3.0 或更高版本,则有可能。
See Anonymous Functionsin the manual.
请参阅手册中的匿名函数。
In your case, you would define exampleMethodlike this:
在你的情况下,你会这样定义exampleMethod:
function exampleMethod($anonFunc) {
//execute anonymous function
$anonFunc();
}
回答by webbiedave
Just to add to the others, you can pass a function name:
只是为了添加到其他人,您可以传递一个函数名称:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
This will work in PHP4.
这将在 PHP4 中工作。
回答by Jage
You can also use create_functionto create a function as a variable and pass it around. Though, I like the feeling of anonymous functionsbetter. Go zombat.
您还可以使用create_function将函数创建为变量并将其传递。不过,我更喜欢匿名函数的感觉。去僵尸。
回答by Saint Night
Just code it like this:
只需像这样编码:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
it would be great if you could invent something like this (inspired by Laravel Illuminate):
如果你能发明这样的东西(灵感来自 Laravel Illuminate),那就太好了:
Object::method("param_1", function($param){
$param->something();
});
回答by Nick Tsai
According to @zombat's answer, it's better to validate the Anonymous Functions first:
根据@zombat 的回答,最好先验证匿名函数:
function exampleMethod($anonFunc) {
//execute anonymous function
if (is_callable($anonFunc)) {
$anonFunc();
}
}
Or validate argument type since PHP 5.4.0:
或者验证自 PHP 5.4.0 起的参数类型:
function exampleMethod(callable $anonFunc) {}
回答by Davit Gabrielyan
PHP VERSION >= 5.3.0
PHP 版本 >= 5.3.0
Example 1: basic
示例 1:基本
function test($test_param, $my_function) {
return $my_function($test_param);
}
test("param", function($param) {
echo $param;
}); //will echo "param"
Example 2: std object
示例 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;
});
Example 3: non static class call
示例 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;
});
Example 4: static class call
示例 4:静态类调用
class obj {
public static function test($test_param, $my_function) {
return $my_function($test_param);
}
}
obj::test("param", function($param) {
echo $param;
});
回答by Marco Ottina
Tested for PHP 5.3
已针对 PHP 5.3 进行测试
As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php
正如我在这里看到的,匿名函数可以帮助你:http: //php.net/manual/en/functions.anonymous.php
What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.
您可能需要什么,在如何传递函数而不将其包装在动态创建的函数中之前并没有说明。稍后您将看到,您需要将写入字符串的函数名称作为参数传递,检查其“可调用性”,然后调用它。
The function to do check:
做检查的功能:
if( is_callable( $string_function_name ) ){
/*perform the call*/
}
Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php
然后,调用它,使用这段代码(如果你还需要参数,把它们放在一个数组上),见:http: //php.net/manual/en/function.call-user-func.php
call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );
as it follows (in a similar, parameterless, way):
如下(以类似的无参数方式):
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");
Here's a class explaining how to do something similar :
这是一个解释如何做类似事情的课程:
<?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);
}
}
}
?>
and an example of usage
和使用示例
<?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's 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's 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 's override specify"*/
/*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
$obj->justPrintSomething("Hyman 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's a name used to identify both
a value (into the dictionary of values) or a function-name
(into the dictionary of functions)*/
?>
回答by Softmixt
Simple example using a class :
使用类的简单示例:
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;
});

