0

I have a function that returns an object. How to write a string that parses a member of the object returned by that function (the function is in a different namespace)? This is what I'm trying to do but the string used on echo is invalid.

namespace security;
function &get_user() {
    $user = (object) array('email' => 'abcd@abcd.com', 'name' => 'John Doe');
    return $user;
}

echo "<li><p class=\"navbar-text\">Welcome, {${\security\get_user()}->name}</p></li>";
Eduardo
  • 5,645
  • 4
  • 49
  • 57

2 Answers2

3

Well, a few things:

  • You cannot interpolate functions/method inside strings. Only variables are allowed.
  • When you create a namespace you only have to refer to it when outside the namespace.
  • Do not use references (&) unless you understand what they do. In PHP references work differently than in most other languages.

This is how the code will look like.

// We define the namespace here. We do not need
// to refer to it when inside the namespace.
namespace security;

// Objects and arrays are always passed by
// reference, so you should not use & here
function get_user() {
    return (object) array(
        'email' => 'abcd@abcd.com',
        'name' => 'John Doe',
    );
}
// We need to get the value from the function
// before interpolating it in the string
$user = get_user();

// There are a few ways to interpolate in PHP
// This is for historical and functional reasons
// Interpolating array items is, "{$arr['key']}"
echo "<li><p class=\"navbar-text\">Welcome, $user->name</p></li>";
echo "<li><p class=\"navbar-text\">Welcome, {$user->name}</p></li>";
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
  • More precisely, you can use functions/methods inside strings, but they are expected to return a variable name. – Tgr Sep 01 '13 at 23:47
  • 1
    It is also possible to use this: `echo "
  • Welcome, " . get_user()->name . "

  • ";` if the more-concise source code is truly needed. – ash Sep 01 '13 at 23:50
  • Actually the `echo` is inside another php file and namespace. That's why I put namespace. I read the docs and think I understand references and their caveats (http://stackoverflow.com/questions/3307409/php-pass-by-reference-in-foreach) but I still don't understand the implications of returning a reference on the `get_user` function. – Eduardo Sep 02 '13 at 02:25