-2

I need to call a function inside a method. This function needs access to a private property. This code:

class tc {
  private $data=123;

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

    test2();
  }
}

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

returns the following error:

Fatal error: Using $this when not in object context in ... on line ...

Using PHP 5.6.38. How can I do this?

dj50
  • 51
  • 8

1 Answers1

1

Not sure why would you declare a function inside a method, but if that is what you want to do, then pass the private member as a parameter to this function.

<?php 

class tc {
  private $data=123;

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

    test2($this->data);
  }

}

$a=new tc();
$a->test();
nice_dev
  • 17,053
  • 2
  • 21
  • 35