In PHP we can do things like this:
$who = 'world';
$a = 'hello ' . $who;
or
$a = "hello $who";
or
$a = "hello {$who}"
Quoting Stephen Clay from php.net into the String operators section the last way is the best because when we use dots PHP is forced to re-concatenate all string. Also if we need to concat more variables, the last is a better way than the second way. But, Which is the best way if I have to concat a value from a class static variable ? PHP throws error if you try to concat the variable directly into a namespace class, without using dots. Only the first way shown before is allowed. I want to know if there is some another way to do this
ERROR:
$a = "hello
amespace\classname::$who"; //NOTICE: undefined variable who
$b = "hello ${
amespace\classname::$who}"; //NOTICE: undefind variable classname
$c = "hello
amespace\classname::${who}"; //NOTICE: undefine variable who.
$d = "hello {
amespace\classname::$who}"; //NOTICE: undefine variable who
I tried to explain with simple code, the really is that I need to concat a static variable from a class who I can't get an instance. If you get some class into a variable and later try to concat the static property this run correctly also
$who = new
amespace\classname();
$a = "{$who::$who} $a"; // this run ok.
The problem with something like...
$d = "hello {
amespace\classname::$who}"
is that the {}
would normally expect just a variable to do a substitution, but as it sees amespace\classname
is wouldn't know if this was a literal piece of text or not, so it defaults to being a literal and then gets to $who
and so looks for a variable in the current namespace.
If you can't get an instance of the class, you can still set a variable with the name of the class...
$class = namespace\classname::class;
echo "Hello {$class::$who}";
Which is the best way if I have to concat a value from a class static variable
The one that works. These are micro-optimizations and usually does not have any measurable impact on performance. Choose the version which is more readable for you and use it:
$who =
amespace\classname::$who;
$a = "hello {$who}";
or
$a = 'hello ' .
amespace\classname::$who;
And then focus on more important things. I'm sure your app has plenty places which could be optimized and give some measurable performance improvements, don't waste time on such low-level stuff (unless your app is only concatenating strings :P).