2011-01-30 57 views
4

請看看下面的代碼:從另一個對象獲取主叫類實例

class Foo { 

    public $barInstance; 

    public function test() { 
     $this->barInstance = new Bar(); 
     $this->barInstance->fooInstance = $this; 
     $this->barInstance->doSomethingWithFoo(); 
    } 

} 

class Bar { 
    public $fooInstance; 

    public function doSomethingWithFoo() { 
     $this->fooInstance->something(); 
    } 
} 

$foo = new Foo(); 
$foo->test(); 

問題:是否有可能讓「$barInstance"知道從哪個類創建它(或稱),而無需在以下字符串:"$this->barInstance->fooInstance = $this;"

+1

No.(fillin text) – mhitza 2011-01-30 03:52:17

+0

您爲避免該行的動機是什麼?你還沒有提供。 – erisco 2011-01-30 07:17:34

回答

3

從理論上講,你也許能debug_backtrace()做到這一點,這是 在堆棧跟蹤的對象,但你最好不要做,這不是良好的編碼,我認爲你的最好方式在Bar的ctor中傳遞父對象:

class Foo { 

    public $barInstance; 

    public function test() { 
     $this->barInstance = new Bar($this); 
     $this->barInstance->doSomethingWithFoo(); 
    } 
} 

class Bar { 
    protected $fooInstance; 

    public function __construct(Foo $parent) { 
     $this->fooInstance = $parent; 
    } 

    public function doSomethingWithFoo() { 
     $this->fooInstance->something(); 
    } 
} 

這將參數限制爲正確的類型(Foo),如果它不是您想要的類型,請將其刪除。將它傳遞給ctor將確保Bar永不處於doSomethingWithFoo()將失敗的狀態。

相關問題