Forum Moderators: coopster

Message Too Old, No Replies

Variable Scope and String Generation

problem with dividing work into sub-functions

         

mm1220

7:32 pm on Nov 30, 2005 (gmt 0)

10+ Year Member



What I'm trying to do the following:

function getString(){
return "all the way a goal to me $a";
}

function output(){

$a = 45;

$string = getString();

echo $string;

}

The output is: all the way a goal to me

I'd like it to be: all the way a goal to me 45

Obviously $a isn't in scope when the string is created but is there a clever way around this?

jatar_k

10:00 pm on Nov 30, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



have the value passed to the getString function

mm1220

10:27 pm on Nov 30, 2005 (gmt 0)

10+ Year Member



Wow! That was pretty obvious, huh?

Thanks jatar_k

jatar_k

10:34 pm on Nov 30, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



the other thing you could do is give $a a default value. If you are using it in places already or wanted to use it both with and without a parameter

function getString($a=''){
return "all the way a goal to me $a";
}

i think that's the right syntax, I use it so seldom

mm1220

12:57 pm on Dec 1, 2005 (gmt 0)

10+ Year Member



Okay to further complicate matters:

function getString($a, $name){

dbOpen();

$query = "select data from MyTable where name = '$name'";

$result = mysql_query($query);

$row = mysql_fetch_row($result);

mysql_free_result($result);

dbClose();

return $row[0];

}

function output(){

$a = 45;

$string = getString($a, 'cool_name');

echo $string;

}

The MySQL query returns a string:
data, data everywhere $a

The output is: data, data everywhere $a

I'd like it to be: data, data everywhere 45

Thanks again.

coopster

4:25 pm on Dec 1, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could use a str_replace() or an eval(). In this case, str_replace() [php.net] should work fine.
$string = str_replace('$a', $a, $string);