nawfal
nawfal

Reputation: 73233

String interpolation for built-in functions

I have something like this in PHP

$file = "$dir/" . basename($url);

basename is a built-in function. Is there a way I can use string interpolation syntax for concatenation instead of . syntax?

For member functions of a class, this works:

$file = "$dir/ {$this->someFunc($url)}";

How do I similarly specify internal functions in quoted strings? Just learning.

Upvotes: 0

Views: 1630

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

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)
);

Upvotes: 4

Related Questions