Executing functions inside string
Everyone knows in PHP you can do this:
$m = "my string is {$string}";
开发者_运维问答But is taht possibile with function too? Like:
$m = "my string is {getStringValue()}";
The string expansion in {$..}
goes a bit beyond just being able to execute functions. I for example used gettext with that. But you can also use tricks like that:
$html = "htmlentities"; // any callback function
// or just: $html = function($s){ return $s; }
print "even allows expressions {$html(2+3*5+rand(2,17))} here";
That's possible because PHP allows any variable expression there in order to support the simple object notation case:
print "this isn't just a {$obj->prop} string variable";
And for example I'm utilizing an object which implements ArrayAccess, where even this is a method invocation:
print "Makes some things {$_GET->ascii->html['input']} simpler";
We had a few such topics on SO, but for the life of me I can't find a good reference ...
This is not possible (and it wouldn't be very readable too, especially if the function had parameters).
You could use sprintf:
$m = sprintf("my string is %s", getStringValue());
Only variable names are expanded http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
With concatenation, If I understand well what you're trying to do:
$m = "my string is {".getStringValue()."}";
精彩评论