Sar*_*raz 1 php variables scope
有没有一种方法可以读取顶部定义在底部某些位置的变量。这是这种情况的示例:
<!--this image is somewhere on top of the page-->
<img src="/<?php print logoPath(); ?>" border="0" />
// this code is somewhere on bottom of the page
$logo_query = "select logo_path from table where id = $row->user_id";
$res_logo = mysql_query($logo_query) or die(mysql_error());
$row_logo = mysql_fetch_object($res_logo);
$logo_path = $row_logo->logo_path;
function logoPath()
{
global $logo_path;
return $logo_path;
}
Run Code Online (Sandbox Code Playgroud)
我试图使用该函数返回值,但即使这样似乎也不起作用。
有什么办法吗?
谢谢
不,在PHP中,所有指令均按顺序执行,因此您无法读取尚未定义的变量。您必须移动将值设置为$logo_path高于调用logoPath()函数的位置的代码。
或者,您可以将sql代码放在logoPath()函数中,这将使您拥有该函数,该函数可以在调用函数的位置下方返回徽标路径。