Search code examples
phpoopmethodsprivate

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


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?


Solution

  • 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();