2011-12-31 52 views
1

我有,這是一個方法中運行一些代碼(這是一個CakePHP的視圖):

這工作:

$this->foo(); 

這不:

function bar() { 
    $this->foo(); 
} // Using $this when not in object context 

無論是做這個的:

function bar() { 
    global $this; 
    $this->foo(); 
} // Cannot re-assign $this 

這也不:

$that = $this; 
$bar = function() { 
    global $that; 
    $that->foo(); 
} // Trying to get property of non-object 

我想使用該對象的庫函數從該方法中,但bar一直呆在本地子過程(移動它是一個類的方法是沒有意義的)。任何解決方案或解決方法?

+1

你可以將$ this傳遞給函數嗎?酒吧($本); – bumperbox 2011-12-31 21:11:16

+2

從5.4開始,您將能夠在匿名函數中直接引用'$ this'](http://us2.php.net/manual/en/functions.anonymous.php)。 5.4還不適合生產使用。 – Charles 2011-12-31 21:15:17

回答

3

在PHP 5.3:

$that = $this; 
$bar = function() use (&$that) { /* the reference isn't really required 
            since it's an object handle */ 
    $that->foo(); 
}; 

使用PHP 5.4,上述黑客ISN沒有要求。

0

你能做的唯一的事情就是通過這個$作爲參數吧()...

function bar($that) 
{ 
    $that->foo(); 
} 

// and to call from within class method: 
$this->foo($this);