if I have something like below (very basic but I hope you get what I mean)
.
.
html code
.
.
<?php
$string=tru开发者_StackOverflow中文版e;
.
.
?>
.
.
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.
精彩评论