简体   繁体   English

回声内部函数(PHP)

[英]Function inside of an echo (PHP)

I have created a function which returns information about a website, based on an array function. 我创建了一个函数,该函数根据数组函数返回有关网站的信息。 The function works like this: 该函数的工作方式如下:

site_info('sitename');

Which returns: 哪个返回:

Example Site Name

Using a code similar to this: 使用类似于以下的代码:

 function site_info($info) {
     $array = array('sitename' => 'Example Site Name');
     echo $array[$info];
 }

I wish to print these unformatted and then format them after, for example: 我希望先打印这些未格式化的文件,然后再格式化,例如:

echo '<title>'.site_info('sitename').'</title>';

However, this prints into: 但是,这将打印为:

Example Site Name <title></title>

Does anyone have any idea why this is happening? 有谁知道为什么会这样吗? One idea I had was that perhaps because the function is echoing the output, which is then inside of another input it wasn't liking it- if this is the case, is there a work around? 我的一个想法是,可能是因为函数正在回显输出,然后又在另一个输入的内部而不喜欢它-如果是这种情况,是否可以解决?

Use return inside function instead of eacho and make sure you are using correct array key like: 使用return inside函数而不是eacho,并确保使用正确的数组键,例如:

 function site_info($info) {
     $array = array('sitename' => 'Example Site Name');
     return $array['sitename']; // in your case there will be $info as key
 }

You have to return the value from the function - 您必须从函数return值-

 function site_info($info) {
     $array = array('sitename' => 'Example Site Name'); // ' was missing
     return $array[$info];
 }

And then call the function in echo - 然后在echo调用该函数-

echo '<title>' . site_info('sitename') . '</title>'; // ' was missing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM