我今天试过这个代码!但它并没有达到我预期的效果。。这是我的密码。。
<?php
namePrint('Rajitha');
function namePrint($name) {
echo $name;
}
wrap('tobaco');
function wrap($txt) {
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>
此代码将打印在屏幕上
RajithaYour username is tobaco
但是我想要
RajithaRajithaYour username is tobaco
我的问题是:为什么wrap函数中的$name变量不起作用?
谢谢。
永远不要在函数内部使用echo
来输出结果。并且永远不要对变量使用global
。
您在函数内部使用了echo
,因此会得到意外的输出。
echo namePrint('Rajitha');
function namePrint($name){
return $name;
}
echo wrap('tobaco');
function wrap($txt){
//global $name;
return "Your username is ".namePrint('Rajitha')." ".$txt."";
}
输出
使用Codepad 功能中的回波RajithaRajithaYour username is tobaco
Output1
在函数Codepad 中使用返回RajithaYour username is Rajitha tobaco
如果你想把一个函数包装在另一个函数上,你可以简单地传递一个闭包作为参数之一:
function wrap($fn, $txt)
{
echo "Your username is ";
$fn();
echo ' ' . $txt;
}
wrap(function() {
namePrint('Rajitha');
}, 'tobaco');
这种结构非常微妙;使用函数返回值更可靠:
function getFormattedName($name) {
return $name;
}
echo getFormattedName('Jack');
然后,包装功能:
function wrap($fn, $txt)
{
return sprintf("Your username is %s %s", $fn(), $txt);
}
echo wrap(function() {
return getFormattedName('Jack');
}, 'tobaco');
另一个选项是将$name作为参数传递给wrap函数。
<?php
$name = 'Rajitha';
function namePrint($name){
echo $name;
}
function wrap($txt, $name){
echo "Your username is " . $name . " ". $txt;
}
namePrint($name);
wrap('tobaco', $name);
?>
$name应该声明并初始化为全局变量。然后您就可以获得所需的输出。
代码应该是这样的。
<?php
$name = 'Rajitha';
namePrint($name);
function namePrint($name){
echo $name;
}
wrap('tobaco');
function wrap($txt){
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>