[PHP] Constants in strings

2011-07-06 Thread Dave Wilson
Hi all,

OK. We all know that constants cannot be accessed directly via their name
in double-quoted or heredoc strings. I knew this already but a read of
the PHP manual got me thinking.

The manual states that to get the $$ value of a variable, the form
{${var}} should be used. Therefore, I wondered if something similar 
would work for constants.

Attempt 1 (just to be sure):
?php
define ('XYZ','ABC');
echo {XYZ}\n;
?

Output - {XYZ}

Attempt 2:
?php
define ('XYZ','ABC');
echo {{XYZ}}\n;
?

Output - {{XYZ}}

No luck there. I did encounter one oddity though:

?php
define ('XYZ','ABC');
echo {${XYZ}}\n;
?

Output:
PHP Notice: Undefined variable: ABC in /home/wilsond/testScripts/l7.php 
on line 3

Which appears to mean that PHP is able to pick up the value of the 
constant and try to access a variable with that name.

Any ideas?

Cheers

Dave

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] Constants in strings

2011-07-06 Thread Dave Wilson
On Wed, 06 Jul 2011 12:56:21 +0100, Stuart Dallas wrote:
 My guess is that the preceding $ causes PHP to interpret the next token
 {XYZ} as a variable or a constant, but without that preceding $ it has
 no way to know you're trying to use a constant. As Curtis points out,
 the only way to insert a constant into a string is through
 concatenation.
 
 -Stuart

OK. I should have made myself clearer - I was making an observation with 
regards to constant parsing in strings rather than looking for advice. My 
bad.

My third example showed that {${XYZ}} would echo the value of the 
variable called the value of XYZ:
?php
define ('XYZ','ABC');

$ABC=huh!;

echo {${XYZ}}\n;
?
Output - huh!

We could easily re-write the 'echo' line above to be:
echo {${constant('XYZ'}}\n;

But my example shows that PHP *is* accessing the value of a constant 
without any jiggery-pokery or hacks (e.g. http://www.php.net/manual/en/
language.types.string.php#91628) as it is retrieving the value of ABC 
from the XYZ constant and then looking for a variable of that name.

I admit that I'm no C coder but it may be possible (note, the word may) 
that a change of code within the PHP source tree will allow us to use 
something like echo {{XYZ}} to access the constant value.

Cheers

Dave


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php