我创建了函数
function do_stuff($text) {
$new_text = nl2br($text);
return $new_text;
}
$result = do_stuff("Hello 'n World!");
//returns "Hello <br /> World!"
我希望能够以某种方式在我的函数中提供另一个简单的内置 PHP 函数,例如 strtoupper(),我需要的不仅仅是 strtoupper(),我需要能够在我的 do_stuff() 函数中提供不同的函数。
说我想做这样的事情。
$result = do_stuff("Hello 'n World!", "strtolower()");
//returns "Hello <br /> World!"
如何在不创建另一个函数的情况下完成这项工作。
function do_stuff($text, $sub_function='') {
$new_text = nl2br($text);
$sub_function($new_text);
return $new_text;
}
$result = do_stuff("Hello 'n World!");
//returns "Hello <br /> World!"
附言只是记住了变量变量,并用谷歌搜索,实际上也有变量函数,可能会自己回答这个问题。
http://php.net/manual/en/functions.variable-functions.php
你在第二个例子中有它。 只需确保检查它是否存在,然后将返回分配给字符串。 这里有一个关于函数接受/要求什么作为参数以及它返回什么的假设:
function do_stuff($text, $function='') {
$new_text = nl2br($text);
if(function_exists($function)) {
$new_text = $function($new_text);
}
return $new_text;
}
$result = do_stuff("Hello 'n World!", "strtoupper");
可调用对象可以是字符串、具有特定格式的数组、使用 function () {};
-syntax 创建的 Closure
类的实例以及直接实现__invoke
的类。您可以将其中任何一个传递给您的函数并使用 $myFunction($params)
或 call_user_func($myFunction, $params)
调用它们。
除了其他答案中已经给出的字符串示例之外,您还可以定义一个(新)函数(闭包)。如果您只需要在一个位置包含的逻辑并且核心功能不合适,这可能特别有用。您还可以包装参数并通过以下方式从定义上下文中传递其他值:
请注意,可调用的类型提示需要 php 5.4+
function yourFunction($text, callable $myFunction) { return $myFunction($text); }
$offset = 5;
echo yourFunction('Hello World', function($text) use($offset) {
return substr($text, $offset);
});
输出:http://3v4l.org/CFMrI
要继续阅读的文档提示:
- http://php.net/manual/en/functions.anonymous.php
- http://php.net/manual/en/language.types.callable.php
你可以像这样调用一个函数:
$fcn = "strtoupper";
$fcn();
以同样的方式(正如您自己发现的那样),您可以拥有变量:
$a = "b";
$b = 4;
$$a; // 4
看起来你快到了,只需要省略第二个参数中的括号:
$result = do_stuff("Hello 'n World!", "strtolower");
然后,经过一些清理后,这应该可以工作:
function do_stuff($text, $sub_function='') {
$new_text = nl2br($text);
if ($sub_function) {
$new_text = $sub_function($new_text);
}
return $new_text;
}