Jump to content

variable scope mixing php and html


rramsey

Recommended Posts

Hi,

 

I know all the ways to work around this, but now I'm just curious.  On php 4.3.x I want to mix blocks of php code and html code and have the variables from one php block accessible in other php blocks.  For example:

 

<?php
global $test;
$test = "hello world";
?>
<html>
<body>
<p>
<?php print "test is:    $test -"; ?>
</p>
<p>
<?php 
global $test; print "test is:    $test -";
?>
</p>
</body>
</html>

 

Both paragraph blocks print the same thing, "test is:    -" with $test having no value.  Is there a way to do this?  Searching brings back so many responses, all about variable scope and using global, that I couldn't find anything.

 

There are about 10 different ways to solve the problem, but I just got curious if this was even possible.

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/204207-variable-scope-mixing-php-and-html/
Share on other sites

Yep, I knew that.  I was experimenting to see if the global function would work in the different blocks.  I didn't see anything on the manual page or in the notes about working between the <?php ?> blocks like it does for functions.  I figured if I left it in, people wouldn't suggest global. :)

 

Session variables would work as well, I guess.

When PHP is processing your script, anything outside the <?php ?> tags not processed, so something like

<?php
//
// php stuff
//
$var = 'stuff';
?>
<html stuff>
<?php
//
//  more php stuff
//
echo $var;
?>

looks like

<?php
//
// php stuff
//
$var = 'stuff';
//
//  more php stuff
//
echo $var
?>

to the PHP Processor.  There are no "blocks". It's all one script.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.