Page 1 of 1

declaring variable inside a variable

Posted: Fri Jul 20, 2007 4:40 am
by arathi
Hi,

I would like to hold a url in a variable. The url contains another variable - e.g.:

$url = '/a_page_name/' . $ref . '/';

My problem is that $ref is declared (via a MySQL query) after $url is declared. Is there a way of 'refreshing' $url once $ref has been declared, so that I only need to declare $url once in my header include file which is included at the beginning of all my pages? I know that I could place it in a separate file which could be included after the MySQL query, but I would rather avoid that if possible.

Posted: Fri Jul 20, 2007 4:45 am
by MalikBB
It's simple: make query to get $ref's value before assigning it to $url.

Re: declaring variable inside a variable

Posted: Fri Jul 20, 2007 5:07 am
by stereofrog
arathi wrote:Is there a way of 'refreshing' $url once $ref has been declared
No, in this form not, but there are many ways around this, for example:

Code: Select all

$url = 'foo $ref bar';
$ref = 'quux';
$result = preg_replace('/\$(\w+)/e', '$0', $url);

or

$url = 'foo $ref bar';
$ref = 'quux';
$result = eval("return "$url";");

or

$url = 'foo %s bar';
$ref = 'quux';
$result = sprintf($url, $ref);

Posted: Fri Jul 20, 2007 5:34 pm
by feyd
I suggest preg_replace_callback() as opposed to using the evaluate flag due to the security hole it creates. Although I would tilt toward sprintf() before that.