Frage

I am trying to do something with variable variables and I got stuck on an object problem. Imagine this class setup:

class A
{
  public $field = 10;
}

class B
{
  public $a;

  public function __construct()
  {
    $this->a = new A();
  }
}

Now everyone knows that this pice of code works:

$a = new A();
$var = 'field';
echo $a->$var; // this will echo 10

Is there any possibility I could make something like this work?:

$b = new B();
$var = 'a->field';
echo $b->$var; // this fails

Note: any option which does not use eval function?

War es hilfreich?

Lösung

You can write a custom __get method on your class to access the childrens property. This works:

class A
{
  public $field = 10;
}

class B
{
  public $a;

  public function __construct()
  {
    $this->a = new A();
  }

  public function __get($property) {
    $scope = $this;

    foreach (explode('->', $property) as $child) {
      if (isset($scope->$child)) {
    $scope = $scope->$child;
      } else {
    throw new Exception('Property ' . $property . ' is not a property of this object');
      }
    }

    return $scope;
  }
}

$b = new B();
$var = 'a->field';
echo $b->$var;

Hope that helps

Andere Tipps

How about using a closure?

$getAField = function($b) {
    return $b->a->field;
};

$b = new B();
echo $getAField($b);

Though, it's only possible in newer versions of PHP.

Or, as a more generic version, something like this:

function getInnerField($b, $path) { // $path is an array representing chain of member names
    foreach($path as $v)
        $b = $b->$v;
    return $b;
}

$b = new B();
echo getInnerField($b, array("a", "field"));

I don't recommend it, but you could use eval:

$b = new B();
$var = 'a->field';
eval( 'echo $b->$'.$var );

This should also work I guess:

$b = new B();
$var1 = 'a'; 
$var2 = 'field'

echo ($b->$var1)->$var2; 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top