简体   繁体   中英

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?

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 .

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>

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM