我有一些代码在一个方法中运行(它是一个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
必须保留本地子过程(将其移动为类方法将毫无意义)。任何解决方案或解决方法?
答案 0 :(得分: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,不需要上述黑客攻击。
答案 1 :(得分:0)
你唯一能做的就是将$ this作为参数传递给bar()...
function bar($that)
{
$that->foo();
}
// and to call from within class method:
$this->foo($this);