carlgcode
carlgcode

Reputation: 255

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

Like this...

 echo $title;

 $title = 'Jelly';

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...

Upvotes: 0

Views: 1431

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157900

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>

Upvotes: 1

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26719

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.

Upvotes: 0

0x6A75616E
0x6A75616E

Reputation: 4716

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.

Upvotes: 1

Related Questions