Richard Knop
Richard Knop

Reputation: 83697

PHP dynamic object property is there a way to make it work?

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;

Upvotes: 0

Views: 4000

Answers (3)

Gordon
Gordon

Reputation: 316969

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".

Upvotes: 1

fuwaneko
fuwaneko

Reputation: 1165

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.

Upvotes: 4

Mark Baker
Mark Baker

Reputation: 212412

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};

Upvotes: 2

Related Questions