我想知道是否可以将回声输出到变量中。我的意思是echo需要多个参数,所以我可以使用echo输出类似于的东西
echo 'Welcome ', $name, ', we are here to help!';
我发现它比串联字符串更干净、更容易维护,而且我无法忍受复杂的语法。是否可以使echo只返回一个值?所以我可以做一些类似的事情
$string_not_meant_for_being_displayed = echo('Lorem', $ipsum);
或者,是否可以创建一个接受无限数量参数的函数?
性能实际上不是问题。
是的,可以创建一个接受无限数量参数的函数。您只需要使用func_num_args()
来获得提供的参数数量。
function abcd(){
$numargs = func_num_args();
echo "Number of arguments: $numargsn";
}
abcd(1,2,3,4,5,6);
为什么要将echo存储到变量中?
要使用多个参数,请使用双引号语法:
echo"欢迎$firstname,$lastname。我们在这里提供帮助!";
我对你的问题有点困惑,但关于我如何理解,
在函数内部,不要使用echo,而是使用return。
例如,你有一个功能,
function myFunction()
{
$name = "Leonardo";
return $name;
}
在这种情况下,您可以将返回的值用作变量。因此$name变量现在的值为"Leonardo";
用户sprintf
、vsprintf
、printf
而非
http://php.net/manual/en/function.sprintf.php
http://www.php.net/manual/en/function.vsprintf.php
http://www.php.net/manual/en/function.printf.php
如果必须使用echo,我相信您希望研究使用输出缓冲:ob_start和ob_get_flush。
示例:
ob_start();
echo "This is a test";
$string_not_meant_to_be_displayed = ob_get_flush();
这样的东西怎么了。。。
$name='Goober';
$thing="Welcome $name, we are here to help!";
echo $thing;
echo "n";
这个怎么样??
<?php
function extended_echo($text, $values) {
$count = 1;
foreach ($values as $values) {
$text = preg_replace("#@" . $count . "@#", $values, $text);
$count++;
}
return $text;
}
$myValues = array();
$myValues[0] = 'TechNew.In';
$myValues[2] = 'tech';
$myValues[3] = 'dino babu';
$myText = "Hello, @1@ is an awesome @2@ website by @3@.";
echo extended_echo($myText, $myValues);
?>
输出
Hello, TechNew.In is an awesome tech website by dino babu.
我能够解决创建另一个函数的问题,如下所示:
function ee(){
foreach(func_get_args() as $arg) {
$v .= $arg;
}
return $v;
}
$name = "John";
echo ee("Welcome ", $name, ", we are here to help");
$string_not_meant_to_be_displayed = ee("His name is ", $name);
通过这种方式,我可以像echo一样使用多个参数,但如果需要,可以将其输出到其他地方。