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
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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

In your particular case, it's not about the scope of variables, rather the way you are trying to display them.

 

Your best approach is . . .

<?PHP $test = 'test variable'; ?>
<html>
<body>
<p>
<?PHP echo '$test = '.$test; ?>
</p>
</body>
</html>

 

Zagga

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.