comparebest Posted November 25, 2010 Share Posted November 25, 2010 Ok this is some noob question here I have a page that has few separate pieces of php code embeded within html code. Each piece is separated with <?php ... ?> tags, everything works fine. I need to assign a variable in first (from the top) piece of php code. Then I want to be able to use that variable in all others php pieces across this same page.... I searched and searched and first tried to do it like : First piece: <?php function id() { $id="blah"; } ?> Second piece : <?php id(); ... echo $id; ?> didn't work, then I tried First place: <?php $id="blah"; function id() { global $id; } ?> Second piece : <?php echo $id; ?> After struggling and reading for few days all about global, static, and regular variables i finally decided to ask professionals to help.... please let me know if you need me to make the question description more clear or smn Quote Link to comment Share on other sites More sharing options...
mellis95 Posted November 25, 2010 Share Posted November 25, 2010 You can simply declare your variable in the first section, do something else, and the variable is still set in the second set of PHP tags. You can use the variable anywhere in the same page. The problem with the other ways you were trying to do it is that the functions make the variable private to that function and cannot be accessed outside of the function the way you were trying. <?php $id="blah"; ?> <html>....some html here.... <?php echo $id; ?> more html here...... </html> I think you are overcomplicating it. Quote Link to comment Share on other sites More sharing options...
darkfreaks Posted November 25, 2010 Share Posted November 25, 2010 index.php class id { protected $id; public function __construct { $this->id= $id; } } newpage.php include('index.php'); echo new id($id); Quote Link to comment Share on other sites More sharing options...
trq Posted November 26, 2010 Share Posted November 26, 2010 index.php class id { protected $id; public function __construct { $this->id= $id; } } newpage.php include('index.php'); echo new id($id); You cannot simply echo an Object, nor would you, In such a simple case need one. Ridiculous. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.