【问题标题】:PHP: Read a variable at top present at bottomPHP:在底部读取顶部的变量
【发布时间】:2009-12-07 10:27:15
【问题描述】:

有没有办法读取顶部的变量,该变量在底部的某个位置定义。 下面是这种情况的一个例子:

<!--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;
}

我尝试使用该函数返回值,但即使这样似乎也不起作用。

有什么办法吗?

谢谢

【问题讨论】:

    标签: php variables scope


    【解决方案1】:

    不,在 PHP 中,所有指令都是按顺序执行的,因此您无法读取尚未定义的变量。您必须将设置 $logo_path 值的代码移到调用 logoPath() 函数的位置上方。

    或者,您可以将 sql 代码放在 logoPath() 函数中,这将允许您拥有在调用函数的位置下方返回徽标路径的函数。

    【讨论】:

      【解决方案2】:

      没有,但是有一种方法可以用 jquery 来做到这一点:

      <img id="image" src="" 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;
              echo "<script type='text/javascript'> $('#image').src('".$logo_path."');</script>";
      }
      

      这有点愚蠢,但应该可以。

      【讨论】:

        【解决方案3】:

        您可以做的是使用 Div 标签并将位置放在页面顶部。这样代码可以在按钮处执行,但结果会显示在顶部。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-30
          相关资源
          最近更新 更多