我找不到我的问题的答案,我想我错过了一些容易的东西。
我试图在一个类的变量中引用一个对象中的一个值。在本例中,我想在底部添加一行:
echo $b->ref->$a->type
输出'testing',就像下面两个一样:
echo $b->ref->test; // outputs 'testing'
$c = $a->type;
echo $b->ref->$c; // outputs 'testing'
完整代码:
<?php
class A {
public $type;
public function set_type($type) {
$this->type = $type;
}
}
class B {
public $ref;
public function set_reference($ref) {
$this->ref = $ref;
}
}
$a = new A();
$b = new B();
$b->set_reference( (object) array('test' => 'testing', 'test2' => 'testing2') );
$a->set_type('test');
echo $b->ref->test; // outputs 'testing'
echo '<br />';
echo $a->type; // outputs 'test'
echo '<br />';
$c = $a->type;
echo $b->ref->$c; // outputs 'testing'
echo '<br />';
echo $b->ref->$a->type; // error
我错过了什么才能做到这一点?或者,这是不可能的吗?
一如既往
echo $b->ref->{$a->type};
你试过了吗:
echo $b->ref->{$c};