Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable string parsing in PHP

Pretty straightforward; I've read through the docs but perhaps I'm just a tad confused by the explanation.

class Test{
    public static $var = 'world';
}

echo "hello {Test::$var}"; // only parses $var in current scope, which is empty

Is there any way to achieve the desired functionality here? I'm starting to guess no, as I've tried a number of permutations with no success.

Clarification: I'm trying to achieve this with PHP's variable parsing, not concatenation. Obviously I'll resort to concatenation if the desired method is not possible, though I'm hoping it is.

like image 728
Dan Lugg Avatar asked May 08 '11 20:05

Dan Lugg


People also ask

How to assign string value in PHP?

PHP string literal php $a = "PHP"; $b = 'PERL'; echo $a, $b; In this code example, we create two strings and assign them to $a and $b variables. We print them with the echo keyword. The first string is created with the double quote delimiters, the second one with single quotes.

What is parse_ str in PHP?

Definition and Usage. The parse_str() function parses a query string into variables. Note: If the array parameter is not set, variables set by this function will overwrite existing variables of the same name. Note: The magic_quotes_gpc setting in the php. ini file affects the output of this function.

How to make a string literal in PHP?

We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string in PHP. For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use double backslash (\\).

How to use single quote in string PHP?

Single quoted ¶ The simplest way to specify a string is to enclose it in single quotes (the character ' ). To specify a literal single quote, escape it with a backslash ( \ ). To specify a literal backslash, double it ( \\ ).


1 Answers

Variable parsing in PHPs double quoted strings only works for "variable expressions". And these must always start with the byte sequence {$. Your reference to a static identifier however starts with {T hencewhy PHP parses towards the next $ in your double quotes and ignores Test::

You need to utilize some cheat codes there. Either use a NOP wrapper function:

$html = "htmlentities";
print "Hello {$html(Test::$var)}";

Or pre-define the class name as variable:

$Test = "Test";
print "Hello {$Test::$var}";

I'm afraid there's no native way to accomplish this otherwise.

like image 106
mario Avatar answered Nov 03 '22 11:11

mario