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

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

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.

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.