PHP在另一个自定义函数中使用不同的自定义函数
我已经创建了函数PHP在另一个自定义函数中使用不同的自定义函数,php,function,Php,Function,我已经创建了函数 function do_stuff($text) { $new_text = nl2br($text); return $new_text; } $result = do_stuff("Hello \n World!"); //returns "Hello <br /> World!" 函数do_stuff($text){ $new_text=nl2br($text); 返回$new_text; } $result=do_stuff(“Hello
function do_stuff($text) {
$new_text = nl2br($text);
return $new_text;
}
$result = do_stuff("Hello \n World!");
//returns "Hello <br /> World!"
函数do_stuff($text){
$new_text=nl2br($text);
返回$new_text;
}
$result=do_stuff(“Hello\n World!”);
//返回“你好
世界!”
我希望能够在我的函数中提供另一个简单的内置PHP函数,例如strotupper(),不知何故,我需要的不仅仅是strotupper(),我还需要能够在我的do_stuff()函数中提供不同的函数
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!"
说我想做这样的事
$result = do_stuff("Hello \n World!", "strtolower()");
//returns "Hello <br /> World!"
$result=do_stuff(“Hello\n World!”,“strtolower()”;
//返回“你好
世界!”
我如何在不创建其他函数的情况下使其工作
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!"
函数do_stuff($text,$sub_函数=“”){
$new_text=nl2br($text);
$sub_函数($new_文本);
返回$new_text;
}
$result=do_stuff(“Hello\n World!”);
//返回“你好
世界!”
p.S.刚刚记住了变量,谷歌搜索到,实际上也有变量函数,我自己可能会回答这个问题
您可以调用如下函数:
$fcn = "strtoupper";
$fcn();
用同样的方法(正如你自己发现的那样),你可以有变量:
$a = "b";
$b = 4;
$$a; // 4
在你的第二个例子中有。只需确保检查它是否存在,然后将返回值分配给字符串。这里有一个关于函数接受/需要哪些参数以及返回哪些参数的假设:
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");
看起来差不多了,只需在第二个参数中去掉括号:
$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;
}
可调用项可以是字符串、具有特定格式的数组、使用
函数(){}创建的闭包
类的实例代码>-语法和类实现\u直接调用。您可以将其中任何一个传递给函数,并使用$myFunction($params)
或call\u user\u func($myFunction,$params)
调用它们
除了其他答案中已经给出的字符串示例外,您还可以定义一个(新)函数(闭包)。如果您只需要在一个地方使用包含的逻辑,而核心函数不合适,那么这可能特别有用。您还可以通过以下方式包装参数并从定义上下文传递其他值:
请注意,可调用类型提示需要PHP5.4+
function yourFunction($text, callable $myFunction) { return $myFunction($text); }
$offset = 5;
echo yourFunction('Hello World', function($text) use($offset) {
return substr($text, $offset);
});
输出:
要阅读的文档提示:
我不明白。你所要求的在你的第二个例子中已经实现了。第二个例子有效吗?我只是随便编出来的。编辑哇,它确实有用,我只是忘了给$new_文本变量指定子函数值:)可能是重复的谢谢你是第一个。如何将多个参数传递给函数say if$function=“str\u ireplace”代码>?最后使用了call\u user\u func\u数组(“function”,$args\u arr)
,因为它支持任意顺序的多个参数,例如,我可以同时执行str\u ireplace(“find”),和stristr($text,“find”)
,它们的参数顺序不同