tags:

views:

62

answers:

7

I tried to call foo() inside a string like this:

echo "This is a ${foo()} car";

function foo() {
    return "blue";
}

but, it ends up with a syntax error.

I found here something similar, but not exactly what I need:

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

Is that possible to do this ?

+2  A: 

No, as far as I know you can only do:

echo "hello ".foo();

function foo() {
    return "world";
}

In your example, this would work:

$name = "captaintokyo";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";

function getName()
{
    return "name";
}

// Output:
// This is the value of the var named by the return value of getName(): captaintokyo
captaintokyo
A: 

${} syntax looks like shell command substitution, for PHP you could use eval, http://php.net/eval

But be warned eval is evil... You must be sure you know what you pass on to eval.

Call it like this:

<?php echo eval("foo();");
CodeReaper
You should not be quoting about eval's flaws when your flaw is what we call owned :/
RobertPitt
A: 

You might as well do this:

echo foo();

zilverdistel
+2  A: 

Not like that, no... you could:

echo "$(" . foo() . ");";
Fosco
A: 

Wrap the $ within single quotes so it does not isn't to me literal, and use concatenation to append the value of foo

echo '$' . foo();

function foo() {
    return "hello";
}

prints : $hello

RobertPitt
A: 

The example you gave:

function foo() {return "hello";}
echo "${foo()}";

This example won't work because using functions in PHP's {$} format only allows you to access the result as a variable name and then show the contents of that variable.

In your example, the echo statement will be trying to echo the contents of a variable named $hello.

To see why it isn't working, we need to modify the example:

function foo() {return "hello";}
$hello="world";
echo "${foo()}";

This program will print world. It seems that this is what you've found in the second example you gave.

If you're hoping to get a program that will print hello in your example, you won't be able to do it using this technique. The good news, however, is that there are plenty of much easier ways to do it. Just echo the function return value.

Spudley
+3  A: 

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.

wimvds
Thanks, you convinced me !
Misha Moroshko