我可以通过函数参数传递一些代码给PHP函数来执行吗?


Can I pass a PHP function some code to execute via a function argument?

新手问题…

是否可以使用函数的参数来传递要在函数内部执行的代码?类似…

function myfunction($somecode)
{
    $somecode;
}
myfunction("echo 'foo'");

实际场景:我的函数执行一些图像处理使用Imagick…

function myfunction($imagePath)
{
    $image = new Imagick($imagePath);
    $image->gaussianBlurImage(0, 5);
}
myfunction("test.jpg");

我希望能够在函数参数中指定图像上使用的Imagick方法,所以我可以有像…

function myfunction($imagePath, $method)
{
    $image = new Imagick($imagePath);
    $image->$method;
}
myfunction("test.jpg", "thumbnailImage(100, 100)");

这种事可能吗?

除了使用匿名函数和可变变量,还可以使用call_user_func_array

function myfunction($imagePath, $method, array $arguments)
{
    $image = new Imagick($imagePath);
    call_user_func_array([$image, $method], $arguments);
}
myfunction("test.jpg", "thumbnailImage", [100,100]);

为了额外的安全,您可以根据Imagick对象可用方法的白名单检查这些方法。

PHP编程 (Lerdorf, Tatroe, &麦金太尔),第二版。第3章,第73页

匿名函数

"您可以使用create_function()创建一个匿名函数"

PHP Manual: create_function()
$lamda = create_function( '$param1,param2', 'code;' );

但是,在PHP 5.3和更高版本中有更多要知道的。摘自PHP手册示例#2中的匿名函数

$greet = function($name)
{
    printf("Hello %s'r'n", $name);
};

PHP手册:匿名函数