0

I am using the following as an example posted on the php manual that should let me use the return value of a method call inside a string...

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

function getName()
{
    return "Bob";    
}

However I get an error: "Notice: Undefined variable: Bob"

This example is from the php manual here: http://php.net/manual/en/language.types.string.php

Is the manual wrong or am i doing something wrong here?

2
  • Assign a value to $Bob and you'll be just fine... Commented Apr 1, 2013 at 21:43
  • If you're going to be building strings with method calls, I suggest assigning them to a variable or at least keeping the method call outside of the string itself. It can get messy (as you can see...). Commented Apr 1, 2013 at 21:44

2 Answers 2

2

You now have this:

"... {$getName()}"

This means that PHP is running the getName() function, gets Bob back and then reads:

"... {$Bob}"

Now, he is trying to get the variable $Bob (because variables are parsed in double quotes).

The solution is to use single quotes and put the function call outside the string:

'... {$'.getName().'}'

Or escape it:

"... \{\$getName()\}"
Sign up to request clarification or add additional context in comments.

3 Comments

alternativately, there's variable functions. $x = 'getName'; echo "{$x()}";. Not that I recommend using them, but they do come in handy on occasion.
@MarcB is that working, to me it looks like it will try to call x() and then $<return-value-of-x>
nope. php will expand $x first, so it becomes "{getName()}", then execute the getName function. however, having a literal echo "{getName()}" will not work - it only works on variable expansion.
1

You could do it like this and it should do what you inteded

echo "This is the value of the var named by the return value of ".getName();

function getName()
{
    return "Bob";    
}

Hope this is helping you

1 Comment

I know, but i am trying to understand php better from the ground up. The manual says this should be possible and provides this example

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.