0

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?

4
  • 1
    did you mean echo $b->$var? Commented Apr 18, 2012 at 19:09
  • yes I did and it should be fixed now Commented Apr 18, 2012 at 19:10
  • True, but I don't think that would work. Commented Apr 18, 2012 at 19:11
  • Well it doesnt work :) That is the question, how to make it work...how to write the code so something like that works if it is even possible Commented Apr 18, 2012 at 19:12

4 Answers 4

2

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"));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

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

Comments

0

This should also work I guess:

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

echo ($b->$var1)->$var2; 

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.