嵌套函数属性可访问性

问题描述 投票:0回答:2

我想在下面的示例中访问testProperty,但这是在嵌套函数内部(扩展twig,它必须嵌套),但它当然说“在不在对象上下文中时使用$ this”。

我根本无法打开现有的“公共功能”。有谁知道如何解决这一问题?

我想在整个类中使用全局变量,而不使用全局变量。

class test
{
    private testProperty;

    public function testFunction() {
        function abc() {
            var_dump($this->testProperty)
        }
    }
}
php properties scope twig this
2个回答
0
投票

我并没有像我想要的那样完全解决问题,但我确实在我的文档中修复了它。我将我的功能放在了外面,并将其公开,只是将我的abc()更改为$ this-> abc()真的对我的疏忽


0
投票

如果我猜测你想要达到的目的是正确的,你可能想做这样的事情:

class test
{
    private $testProperty = "whatever";

    public function testFunction() {

        $abc = function() {
            var_dump($this->testProperty);
        };

        $abc();

    }

}

$x = new test;
$x->testFunction();

由于$abc现在是一个匿名函数,因此在类方法中使用时,它具有$this变量。

上面的代码将输出:

string(8) "whatever"

© www.soinside.com 2019 - 2024. All rights reserved.