我可以在输出变量后声明一个变量??? PHP

时间:2011-09-11 21:37:37

标签: php variables

喜欢这个......

 echo $title;

 $title = 'Jelly';

我只是问,因为我之前有一个头文件我在我的一些页面上声明了$ title,尽管页面有不同的部分使用简单的$ _GET ['tab'] ==='blahblahblah';

但是这些$ _GET变量是在我调用头文件后声明的......

3 个答案:

答案 0 :(得分:1)

没有。如果输出$ title,除非事先将$ title设置为其他内容,否则它将不输出任何内容,或者除非你启用了php的register_globals设置(php< 5.3.0)并且“title”恰好是请求参数。

如果你问你是否被允许这样做,那绝对是。该变量将更改为“Jelly”,但该特定值不会如上所述回显。

答案 1 :(得分:1)

  

但是这些$ _GET变量是在我调用头文件后声明的......

这就是你做错了。

只有在获得所有必要数据后才能调用标题。

您需要适当的网站架构。
将您的代码分为3部分:

  1. 主网站模板(包括您的标题)
  2. 特定页面模板
  3. 页码。
  4. 使用此设置的答案,您将永远不会遇到这样的问题。
    典型的脚本可能看起来像

    <?
    //include our settings, connect to database etc.
    include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
    //getting required data
    $DATA=dbgetarr("SELECT * FROM links");
    // setting title for using in the main template
    $pagetitle = "Links to friend sites";
    //etc
    //set page template filename
    $tpl = "links.tpl.php";
    //and then finally call a template:
    include "main.tpl.php";
    ?>
    

    其中main.tpl.php是您的主要网站模板,包括常见部分,如页眉,页脚,菜单等:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>My site. <?=$pagetitle?></title>
    </head>
    <body>
    <div id="page">
    <? include $tpl ?>
    </div>
    </body>
    </html>
    

    links.tpl.php是实际的页面模板:

    <h2><?=$pagetitle?></h2>
    <ul>
    <? foreach($DATA as $row): ?>
    <li><a href="<?=$row['link']?>" target="_blank"><?=$row['name']?></a></li>
    <? endforeach ?>
    <ul>
    

答案 2 :(得分:0)

在声明之前不应该使用$ title(PHP会产生关于使用未声明变量的通知,并且不会输出任何内容,因为$ title的值将为null)。 $ _GET变量由环境(Web服务器)设置,您不应该为它们赋值 - 您应该只读取$ _GET变量中收到的值。