2011-12-31 33 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);