变量变量 + 字段中的对象


variable variables + objects in fields

我正在尝试用变量做一些事情,但我卡在一个对象问题上。想象一下这样的类设置:

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

现在每个人都知道这几段代码是有效的:

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

我有没有可能做这样的事情?

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

注意:任何不使用评估函数的选项?

使用闭包怎么样?

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

不过,这只能在较新版本的 PHP 中实现。

或者,作为更通用的版本,如下所示:

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"));

可以在类上编写自定义__get方法来访问 childs 属性。这有效:

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;

希望有帮助

我不推荐它,但你可以使用 eval:

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

我想这也应该有效:

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