开发者

Static variable string parsing in PHP

Pretty straightforward; I've read through the d开发者_运维知识库ocs 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.


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.


This works with the string concatenation operator ( . )

echo "hello ".Test::$var; 

EDIT

Note: Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

Source Via This answer


You can always break the echo up into the smaller pieces.

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

echo "hello ", Test::$var;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜