Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问PHP中方法中定义的函数内的属性_Php_Oop_Methods_Private - Fatal编程技术网

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

访问PHP中方法中定义的函数内的属性,php,oop,methods,private,Php,Oop,Methods,Private,我需要在一个方法中调用一个函数。此函数需要访问私有属性。此代码: class tc { private $data=123; public function test() { function test2() { echo $this->data; } test2(); } } $a=new tc(); $a->test(); 返回以下错误: 致命错误:在中不在对象上下文中时使用$this。。。在线… 使用PHP5.6.38。如

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

class tc {
  private $data=123;

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

    test2();
  }
}

$a=new tc();
$a->test();
返回以下错误:

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


使用PHP5.6.38。如何执行此操作?

不确定为什么要在方法中声明函数,但如果您希望这样做,请将私有成员作为参数传递给此函数

<?php 

class tc {
  private $data=123;

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

    test2($this->data);
  }

}

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

因为test2是测试方法中的函数,而不是tc对象中的方法。您不在对象范围内。而且属性是私有的,这意味着您不能访问对象之外的内容。但是,我如何才能做到这一点?为什么不将
test2
作为一个真正的方法,而不是嵌套它呢?test2包含在另一个文件中。这似乎是答案。@dj50很乐意提供帮助。