0

So I know I can do something like this in PHP:

<?php

    $x = 'a';
    $a = 5;
    echo $$x;

Which will output 5;

But it doesn't work with objects/properties. Is there a way to make this code work?

<?php

class FooBar
{
 public $foo;
 public $bar;

 public function __construct()
 {
  $this->foo = 'foo';
  $this->bar = 'bar';
 }
}

$FooBar = new FooBar();

$str = 'FooBar->foo';

echo $$str;

3 Answers 3

4
class FooBar
{
 public $foo;
 public $bar;

 public function __construct()
 {
  $this->foo = 'foo';
  $this->bar = 'bar';
 }
 public function getFoo()
 {
  return $this->foo;
 }
}
$fb = new FooBar();
$classname = "fb";
$varname = "bar";

echo call_user_func(array($fb, "getFoo")); // output "foo"
echo call_user_func(array($$classname, "getFoo")); // same here: "foo"
echo $$classname->{$varname}; // "bar"

See call_user_func manual. Also you can access properties like this: $fb->{$property_name}.

Also there is magic method __get which you can use to work with properties that do not even exist.

Sign up to request clarification or add additional context in comments.

1 Comment

You could also theoretically use the reflection API php.net/reflection , although it'd be pretty verbose and I wouldn't expect performance to be stellar. Specifically, you'd want $o = new ReflectionObject($$classname); echo $o->getProperty($varname);
2

This might be close:

class FooBar
{
 public $foo;
 public $bar;

 public function __construct()
 {
  $this->foo = 'foo';
  $this->bar = 'bar';
 }
}

$FooBar = new FooBar();

$str = 'FooBar->foo';
list($class,$attribute) = explode('->',$str);

echo $$class->{$attribute};

Comments

1

It is not possible to do

$str = 'FooBar->foo'; /* or */ $str = 'FooBar::foo';
echo $$str;

because PHP would have to evaluate the operation to the object or class first. A variable variable takes the value of a variable and treats that as the name of a variable. $FooBar->foo is not a name but an operation. You could do this though:

$str = 'FooBar';
$prop = 'foo';
echo $$str->$prop;

From PHP Manual on Variable Variables:

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Example from Manual:

class foo {
    var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->$baz[1] . "\n";

Both echo calls will output "I am bar".

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.