Maroof Mandal
Maroof Mandal

Reputation: 531

Is it possible to echo a variable which is declared below the echo in PHP?

The below code will not display any output as the variable is declared below the echo as PHP gets executed line by line. Is there any way to search for the variable in the whole page and then execute the code?

<?php
include "header.php";
$title = "Test";
?>

header.php

<html>
<head>
<title><? echo $title ?></title>
</head>

Upvotes: 0

Views: 493

Answers (2)

NullPoiиteя
NullPoiиteя

Reputation: 57322

You need to learn how compilers/interpreters works. PHP is interpreted language and The binary that lets you interpret PHP is compiled.

PHP run from top to bottom.

so its like

<?php // start from here 

   echo "$title";   <-- $title is undefined here
   $title = "Test"; <-- now you declared $title with value so it goes in  memory now

     //end

So you need to first check weather $title is set or not than respond according to it

if(isset($title)){
  echo $title;
}

Upvotes: 5

Blue Rose
Blue Rose

Reputation: 533

According to your logic, I suggest you to use contants like below: Create a separate file, let's say constant.php and include it on all other pages

<?
    define("TITLE", "This is title");

?>

Use it like below:

<?php echo TITLE;?>

Thanks

Upvotes: -1

Related Questions