【问题标题】:Accessing a property inside a function defined in a method in PHP [duplicate]访问PHP中方法中定义的函数内的属性[重复]
【发布时间】:2019-03-30 07:22:34
【问题描述】:

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

class tc {
  private $data=123;

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

    test2();
  }
}

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

返回以下错误:

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

使用 PHP 5.6.38。我该怎么做?

【问题讨论】:

  • 因为 test2 是测试方法中的函数,而不是 tc 对象中的方法。您不在对象范围内。
  • 并且该属性是私有的,也就是说不能在对象之外访问。
  • 不过,我该怎么做呢?
  • 为什么不让test2 成为一个真正的方法而不是嵌套它?
  • test2 包含在另一个文件中。

标签: php oop methods private


【解决方案1】:

不知道为什么要在方法中声明一个函数,但如果这是你想做的,那么将私有成员作为参数传递给这个函数。

<?php 

class tc {
  private $data=123;

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

    test2($this->data);
  }

}

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

【讨论】:

  • 这似乎是答案。
  • @dj50 很高兴为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多