2011-08-09 35 views
0

我無法找到我的問題的答案,我想有一件容易的事,我失蹤了。如何引用具有類變量的對象?

我想在一個類中引用一個變量的對象中的值。在這種情況下,我希望在底部的一行:

echo $b->ref->$a->type 

像下面的兩個輸出「測試」將:

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 

我在想什麼能夠做到這一點?或者,這是不可能的?

回答

2

和往常一樣。

echo $b->ref->{$a->type}; 
+0

謝謝!我知道這是我不知道的簡單事情。我會盡快接受答案。 – bobcat

0

你有沒有試過這樣:

echo $b->ref->{$c}; 
相關問題