我一直在想是否可以在PHP中将一个函数作为参数传递。 我想要类似于JavaScript中编写以下代码时的效果:
object.exampleMethod(function(){
// some stuff to execute
});
我想要的是在 exampleMethod 中执行该函数,这在 PHP 中是否可行?
如果你正在使用 PHP 5.3.0 或更高版本,则可以实现。
请参见手册中的匿名函数。
在你的情况下,你可以像这样定义exampleMethod
:
function exampleMethod($anonFunc) {
//execute anonymous function
$anonFunc();
}
create_function
函数。 - Gordoncreate_function()
来实现一些功能。虽然不完全相同,但你需要将函数作为代码字符串传递,然后在幕后使用eval()
进行处理。这并不是最理想的方法,但你可能可以尝试使用它。 - zombatexampleMethod(strpos);
- sumid补充其他答案,你可以传递一个函数名:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
这在 PHP4 中是可行的。
更新 2022 年 1 月 9 日
按照如下方式编写代码:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
如果您能发明像 Laravel Illuminate 这样的东西,那将是非常棒的:
Object::method("param_1", function($param){
$param->something();
});
function exampleMethod($anonFunc) {
//execute anonymous function
if (is_callable($anonFunc)) {
$anonFunc();
}
}
从PHP 5.4.0开始,或者验证参数类型:
function exampleMethod(callable $anonFunc) {}
PHP版本需大于等于5.3.0
function test($test_param, $my_function) {
return $my_function($test_param);
}
test("param", function($param) {
echo $param;
}); //will echo "param"
$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
return $my_function($test_param);
};
$test = $obj->test;
$test("param", function($param) {
echo $param;
});
class obj{
public function test($test_param, $my_function) {
return $my_function($test_param);
}
}
$obj = new obj();
$obj->test("param", function($param) {
echo $param;
});
class obj {
public static function test($test_param, $my_function) {
return $my_function($test_param);
}
}
obj::test("param", function($param) {
echo $param;
});
测试过适用于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'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("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's a name used to identify both
a value (into the dictionary of values) or a function-name
(into the dictionary of functions)*/
?>
使用类的简单示例:
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;
});
<?php
function valX($value) {
echo "<p>Validating $value == 5</p>";
if ($value == 5) {
return true;
} else {
return false;
}
}
function valY($value) {
echo "<p>Validating $value == 6</p>";
if ($value == 6) {
return true;
} else {
return false;
}
}
function validate($values, $functions) {
for ($i = 0; $i < count($values); $i++) {
if ($functions[$i]($values[$i])) {
echo "<p>$values[$i] passes validation</p>";
} else {
echo "<p>$values[$i] fails validation</p>";
}
}
}
$values = [5, 9];
$functions = ['valX', 'valY'];
validate($values, $functions);
?>