Search code examples
phpoopvariable-variables

variable variables + objects in fields


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?


Solution

  • 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