我知道print_r
打印数组和对象,echo
完成其余的工作。
我的问题是由于我对某些内容进行编码而导致function
的返回变量不会与echo
一起打印,但与print_r
或var_dump
一起打印。鉴于返回的变量是echo
而不是print_r
我觉得我的代码存在问题而不是string
和array
之间存在差异,我很同意
所以我的问题如下:如果我将function showPreviousDiscipline
放在模板中,为什么print_r
只显示它返回的HTML代码?它不应该只显示我在不需要echo
或print_r
的情况下调用该函数吗?在一天结束时只是文本输出
HTML
<div class="ldcMainWrap">
<table>
<tr>
<td>
<select multiple="multiple" size="5">
<?php
// Displays something in the page if is print_r but not if i echo it... or even if i dont put anything...
print_r ($this->showPreviousDiscipline(1));
?>
</select>
</td>
<td>
<select multiple="multiple" size="5">
</select>
</td>
<tr>
</table>
<div>
PHP
public function drawWebsite () {
$tpl = include "step.one.view.php";
return $tpl;
}
public function showPreviousDiscipline ( $uID ) {
$AllUserDetails = parent::$this->pullUserDetails ( $uID );
$allDataRaw = parent::$this->pullDeparmentTableData ();
$html = '';
// Loops through the array $allDataRaw
foreach ($allDataRaw as $key => $val) {
foreach ($val as $key2 => $val2) {
//CHECKs if he user has already selected one and if it does it applies a CSS class
if($key2) {
if($val2 === $AllUserDetails['rID']) {
$html .= '<option value ="'.$val2.'" class="selected">'.$key2.'</option>';
}else {
$html .= '<option value ="'.$val2.'" class="unselected">'.$key2.'</option>';}
}
}
}
$html .= '';
return $html;
}
测试输出
<select multiple="multiple" size="5">
<option value="11" class="unselected">dID</option>
<option value="test1" class="unselected">dName</option>
<option value="" class="unselected">dDescription</option>
<option value="22" class="selected">dID</option>
<option value="test2" class="unselected">dName</option>
<option value="" class="unselected">dDescription</option>
</select>
答案 0 :(得分:0)
来自手册(http://php.net/manual/en/function.echo.php)
echo (unlike some other language constructs) does not behave like a function,
so it cannot always be used in the context of a function.
所以echo(fn())将返回NULL。如果要“回显”函数的值,则需要将值返回到某个局部var并回显该值。或者(如你所见)通过'print_r'调用它。
根据你的问题:
Shouldn't it display only by me calling the function without the need of echo or print_r?
如果在函数中调用echo,print或print_r(而不是指定返回值),它将起作用。现在,你的函数返回一个值但不输出任何东西。