views:

73

answers:

2

Hello All,

Is there a way to read a variable at top which is defined some where at the bottom. Here is an example of such situation:

<!--this image is somewhere on top of the page-->
<img src="/<?php print logoPath(); ?>" border="0" />

// this code is somewhere on bottom of the page
$logo_query = "select logo_path from table where id = $row->user_id";
$res_logo = mysql_query($logo_query) or die(mysql_error());
$row_logo = mysql_fetch_object($res_logo);
$logo_path = $row_logo->logo_path;

function logoPath()
{
 global $logo_path;
 return $logo_path;
}

I tried to use that function to return value but even that doesn't seem to work.

Any solution?

Thanks

+4  A: 

No, in PHP all instructions are executed sequentially so you cannot read a variable that hasn't yet been defined. You must move the code that sets the value of $logo_path above the place where you call the logoPath() function.

Alternatively you could put the sql code in the logoPath() function, which would allow you to have the function that returns the logo path below the place where you call the function.

Yacoby
+1  A: 

No, but there is a way to do it with jquery:

<img id="image" src="" border="0" />

// this code is somewhere on bottom of the page
$logo_query = "select logo_path from table where id = $row->user_id";
$res_logo = mysql_query($logo_query) or die(mysql_error());
$row_logo = mysql_fetch_object($res_logo);
$logo_path = $row_logo->logo_path;

function logoPath()
{
        global $logo_path;
        echo "<script type='text/javascript'> $('#image').src('".$logo_path."');</script>";
}

It's kinda stupid, but it should work.

dfilkovi
yeah i already did so using js. thanks all
Sarfraz