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


can I declare a variable after output of the variable??? php

像这样…

 echo $title;
 $title = 'Jelly';

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

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

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

这就是你做错的地方。

只有在你得到所有必要的数据后才调用你的header。

你需要合适的网站架构。
将代码分成3部分:

  1. 主网站模板(包括你的页眉)
  2. 特定页面模板
  3. 页面代码。

有了这个设置,你永远不会遇到这样的问题。
一个典型的脚本看起来像

<?
//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>

No。如果你输出$title,它将不输出任何东西,除非$title事先设置为其他东西,或者除非你启用了php的register_globals设置(php <5.3.0)和"title"恰好是一个请求参数。

如果你问的是你是否被允许这样做,那当然可以。该变量将被更改为'Jelly',但该特定值不会像上面解释的那样被回显。

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