10

I have a PHP code:

class Test {
    function someThing(){ return 1}
}

$test = new Test();

//why this isn't printing bla bla bla 1????
echo "bla bla bla $test->someThing()";

but it seems like I can't call function inside a double quoted string.

How can I do this?

Thanks.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
The Best
  • 351
  • 2
  • 3
  • 10
  • You cannot, unless you use eval(), which is usually a bad idea. You'd have to get the function call outside of the string. – Calimero Jan 07 '14 at 10:30
  • 1
    ive updated the question to show i need to print some words + return values of a fucntion – The Best Jan 07 '14 at 10:32

4 Answers4

21

You can only call variables inside a string

but if you use {} you can add code to the block

try this:

echo "bla bla bla {$test->someThing()}";
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Nimrod007
  • 9,825
  • 8
  • 48
  • 71
5

You can also put a function name inside a variable and then use that variable like a real function inside double quotes string:

$arr = [1,2,3];
$func_inside_var = 'implode';
echo "output: {$func_inside_var($arr)}" . '<br>';

Note that you can even pass paramater to that call.

hijack
  • 59
  • 1
  • 4
3

Try this way

class Test {
    function someThing()
    {
        return 1;
    }
}

$test = new Test();

echo 'bla bla bla ' . $test->someThing();
sas
  • 2,563
  • 1
  • 20
  • 28
1

you should use this

echo "".$test->someThing()."";

or with out double quoted.

echo $test->someThing();
Ajit Singh
  • 1,132
  • 1
  • 13
  • 24