tags:

views:

37

answers:

3

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;
+2  A: 

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};
Mark Baker
+3  A: 
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.

fuwaneko
+1 for suggestion of __get magic method
Mark Baker
You could also theoretically use the reflection API http://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);`
Frank Farmer
+1  A: 

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

Gordon