开发者

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

Like this...

 echo $title;

 $title = 'J开发者_如何学运维elly';

I only ask because I have a header file before that I declare the $title, on some of my pages though the page has different sections using a simple $_GET['tab'] === 'blahblahblah';

But these $_GET variables are declared after I have called the header file...


But these $_GET variables are declared after I have called the header file...

that's what you're doing wrong.

Call your header only after you've got all necessary data.

You need proper site architecture for this.
Divide your code into 3 parts:

  1. main site template (including your header)
  2. particular page template
  3. page code.

Ans with this setup you'll never run into problem like this.
A typical script may look like

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

where main.tpl.php is your main site template, including common parts, like header, footer, menu etc:

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

and links.tpl.php is the actual page template:

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


No. if you output $title, it will output nothing unless $title has been set to something else beforehand, or unless you have php's register_globals setting enabled (php < 5.3.0) and "title" happens to be a request parameter.

If you're asking whether you're allowed to do it, then absolutely. The variable will be changed to 'Jelly', but that specific value wouldn't have been echoed as explained above.


You should not use $title before you have declared it (PHP will produce notice about using undeclared variable, and won't output anything because value of $title will be null). $_GET variables are set by the environment (the web server) and you should not assign them values - you should just read the values received in the $_GET variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜