Jump to content

use same variable in two or more different closed php tags on same page


comparebest

Recommended Posts

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 :)

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.

 

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.

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.