0

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.

9
  • Not cleanly, interpolation works on variables; but function calls aren't the same as variables Commented Nov 9, 2015 at 10:53
  • You could create a class wrapper that would do the function call for you Commented Nov 9, 2015 at 10:55
  • Alright. I expected there has to be a syntax since something like "{$x->y()}" works. Thanks. Commented Nov 9, 2015 at 10:56
  • @MarkBaker: Assigning the function name to a variable works, though. But you really shouldn't write that kind of messy code Commented Nov 9, 2015 at 10:57
  • @EliasVanOotegem - True. I'd been thinking of something like: class functionCaller { public static function caller($function, ...$args) { return call_user_func_array($function, $args); } } $fc = new functionCaller(); $file = "$dir/{$fc->caller('basename',$url)}" Commented Nov 9, 2015 at 11:00

1 Answer 1

4

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)
);
Sign up to request clarification or add additional context in comments.

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.