Colin
Colin

Reputation: 231

PHP variables retention in html code

if I have something like below (very basic but I hope you get what I mean)

.
. 
html code
.
.
<?php
$string=true;
.
.
?>
.
.
more html

.
.
<?php
if ($string)
.
.
?>

Assuming the page has not been output, Will the value of $string still be available from the previous <?php or does it have to be set up again?

Upvotes: 0

Views: 170

Answers (4)

MrWhite
MrWhite

Reputation: 45889

Short answer... yes it will be.

You can imagine that all your PHP blocks are one as far as variable scope goes. All variables declared in any included files will also be available to you. These variables are in the global scope.

Upvotes: 5

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174967

Yes it will be, the global scope lasts for the entire page, even if there were 100 <?php ?> blocks in the middle (assuming of course, you haven't changed or unset it in the middle of the code).

Do know this, this is a classical TIAS question.

Upvotes: 0

Jared Farrish
Jared Farrish

Reputation: 49208

An example (very similar, incidently, to William's example):

<?php

$string = 'I am a string.';

?>
<html>
<head></head>
<body>
<p><?php echo $string; ?></p>
</body>
</html>

http://codepad.org/X5W769V6

This outputs to the browser:

<html>
<head></head>
<body>
<p>I am a string.</p>
</body>
</html>

This is because PHP is a meant to be parsed within and through html. See PHP Variable Scope.

Upvotes: 0

Will
Will

Reputation: 20235

Your question is a little unclear, but I assume you mean like this:

<?php
$string = "some string";
?>
<html>
<head>
</head>
<body>
    <?php
       // Is $string available here?
       // yes it is.
    ?>
</body>
</html>

Upvotes: 1

Related Questions