7

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.

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mario; I was afraid of that; the lack of native support for my desired functionality. I'll have to hack around to get something close.
1

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

2 Comments

Thanks Gazler; I don't want concatenation though, trying to take advantage of variable parsing.
I do not believe that is possible. Please see this question: stackoverflow.com/questions/1267093/… Especially the link posted as the top answer, which I have quoted in my edits.
0

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

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

echo "hello ", Test::$var;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.