In PHP, How to Call a Function Interpolated in String

PHP interpolating string for function output

The double quote feature in PHP does not evaluate PHP code, it simply replaces variables with their values. If you want to actually evaluate PHP code dynamically (very dangerous), you should use eval:

eval( "function foo() { bar() }" );

Or if you just want to create a function:

$foo = create_function( "", "bar()" );
$foo();

Only use this if there really is no other option.

In PHP, How to call a function interpolated in string?

$str="abcdefg foo() hijklmopqrst";
function foo() {return "bar";}

$replaced = preg_replace_callback("~([a-z]+)\(\)~",
function ($m){
return $m[1]();
}, $str);

output:

$replaced == 'abcdefg bar hijklmopqrst';

This will allow any lower-case letters as function name. If you need any other symbols, add them to the pattern, i.e. [a-zA-Z_].

Be VERY careful which functions you allow to be called. You should at least check if $m[1] contains a whitelisted function to not allow remote code injection attacks.

$allowedFunctions = array("foo", "bar" /*, ...*/);

$replaced = preg_replace_callback("~([a-z]+)\(\)~",
function ($m) use ($allowedFunctions) {
if (!in_array($m[1], $allowedFunctions))
return $m[0]; // Don't replace and maybe add some errors.

return $m[1]();
}, $str);

Testrun on "abcdefg foo() bat() hijklmopqrst" outputs "abcdefg bar bat() hijklmopqrst".

Optimisation for whitelisting approach (building pattern dynamically from allowed function names, i.e. (foo|bar).

$allowedFunctions = array("foo", "bar");

$replaced = preg_replace_callback("~(".implode("|",$allowedFunctions).")\(\)~",
function ($m) {
return $m[1]();
}, $str);

String interpolation for built-in functions

You could do it like so:

$foo = 'bar';

$func = "strtoupper";
echo "test: {$func($foo)}";
//or for assignments:
$path = sprintf(
'%s/%s',
$dir,
basename($file)
);

example here

But really, you shouldn't: it obfuscates what you're actually doing, and makes a trivial task look a lot more complex than it really is (debugging and maintaining this kind of code is a nightmare).

I personally prefer to keep the concatenation, or -if you want- use printf here:

printf(
'Test: %s',
strtoupper($foo)
);

How can I manually interpolate a string?

Here is a possible solution. I am not sure in your particular scenario if this would work for you, but it would definitely cut out the need for so many single and double quotes.

<?php
class a {
function b() {
return "World";
}
}
$c = new a;
echo eval('Hello {$c->b()}.');
?>

How to call a function from a string stored in a variable?

$functionName() or call_user_func($functionName)

Is that possible to expand function call in PHP string?

Is it possible? No.

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.

It's the first note for the curly syntax on http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex.

Php string interpolation

The string interpolation rules are described thoroughly in the PHP manual. Importantly, there are two main styles:

  • One with plain variables in the string, like "the $adjective apple", which also supports some expressions like $foo->bar in "the $foo->bar apple"
  • One with curly brackets, which supports more complex expressions, like {$foo->bar()}, but the expression must start with a $

When PHP sees your string:

  • it first sees {count(, but because the character after { isn't $, it doesn't mean anything special
  • it then sees the $this->movies, which is valid for the first syntax, so it tries to output $this->movies as a string
  • because $this->movies is an array, you get a Warning and the string "Array" is used

The result is that the string will always say "Your collection exists of {count(Array} movies.".


There is no interpolation syntax currently that supports function calls like count(), so you'll have to use concatenation or an intermediate variable:

return "Your collection exists of " . count($this->movies) . " movies.";

or

$movieCount = count($this->movies);
return "Your collection exists of {$movieCount} movies.";

or

$movieCount = count($this->movies);
return "Your collection exists of $movieCount movies.";

Insert a function result in the middle of PHP heredoc

No, there is no better way to do it.

Heredoc string syntax behaves much like double quote string syntax. You can't put a function name as an expression inside of the double quoted string any more than you can a heredoc. So what you're doing is fine and that's how you should be doing it. The only time you can get interpolation inside of string syntax in PHP is if the value is a variable.

For example...

$foo = function() { return 'value'; };
echo <<<SOMEHEREDOC
{$foo()}
SOMEHEREDOC;
// Is the same as
echo "{$foo()}";
// Is the ssame as
$foo = 'strtoupper';
echo "{$foo('hello world')}";

The above code would output

value

value

HELLO WORLD



Related Topics



Leave a reply



Submit