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.
declaring variable inside a variable
Moderator: General Moderators
- stereofrog
- Forum Contributor
- Posts: 386
- Joined: Mon Dec 04, 2006 6:10 am
Re: declaring variable inside a variable
No, in this form not, but there are many ways around this, for example:arathi wrote:Is there a way of 'refreshing' $url once $ref has been declared
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);- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
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.