declaring variable inside a variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
arathi
Forum Newbie
Posts: 6
Joined: Fri Jul 20, 2007 1:40 am

declaring variable inside a variable

Post 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.
MalikBB
Forum Newbie
Posts: 11
Joined: Fri Jul 20, 2007 4:34 am
Contact:

Post by MalikBB »

It's simple: make query to get $ref's value before assigning it to $url.
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Re: declaring variable inside a variable

Post 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);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Post Reply