I need to echo a var in a page but the value is declared later after being included in the page.
Is there any way to echo a var before I declare it? or some way to include the page withought running any of the code and j开发者_如何学运维ust getting the var?
No language is obviously able to output a value, before it exists.
If you want to do something like..
echo $var;
$var = "Hello world";
Then the answer is no. PHP is an interpreted language which runs downwards, not every which way.
The simplest, best and most sensible option is to fix your logic so everything happens in a logical order.
Failing that. Store your data in a variable instead of outputting it. Include a placeholder where you want the variable to be. Then do a search and replace on that placeholder once you have the data you need.
You can build a template-like solution. Put something like ##var##
in the page, use ob_start()
at the beginning of the page, define your $var
whereever, then, at the end of the page, use echo str_replace('##var##', $var, ob_get_clean());
.
Example:
<?php ob_start() ?>
<p>##test##</p>
<?php $test = "this is a test paragraph" ?>
<?php echo str_replace("##test##", $test, ob_get_clean()) ?>
Check out ob_start()
, and ob_get_clean()
.
There is a way to use JavaScript with PHP for this kind of echos.
$echo = document.getElementById('dispaly_div').innerHTML = "$variable";
One way is to use functions.
For example:
function printvar($string) {
echo $string;
}
printvar("Hello World!");
This is tested and works.
精彩评论