Re: Constants in strings

From: Date: Wed, 06 Jul 2011 11:56:21 +0000
Subject: Re: Constants in strings
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-313944@lists.php.net to get a copy of this message
On Wed, Jul 6, 2011 at 12:07 PM, Dave Wilson <dai_bach24@hotmail.com> wrote: > 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? > 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 -- Stuart Dallas 3ft9 Ltd http://3ft9.com/

« previous php.general (#313944) next »