在 PHP 中的方法中定义的函数中访问 属性

Accessing a property inside a function defined in a method in PHP

我需要在一个方法中调用一个函数。此函数需要访问私有 属性。此代码:

class tc {
  private $data=123;

  public function test() {
    function test2() {
      echo $this->data;
    }

    test2();
  }
}

$a=new tc();
$a->test();

returns 出现以下错误:

致命错误:当不在对象上下文中时使用 $this 在线 ...

使用 PHP 5.6.38。我该怎么做?

不确定为什么要在方法内部声明一个函数,但如果这是您想要做的,那么将私有成员作为参数传递给该函数。

<?php 

class tc {
  private $data=123;

  public function test() {
    function test2($data) {
        echo $data;
    }

    test2($this->data);
  }

}

$a=new tc();
$a->test();