How to access a private member inside a static function in PHP

This is a super late response but it may help someone..

class MyClass
{
  private $MyMember;

  public static function MyFunction($class)
  {
    $class->MyMember = 0;
  }
}

That works. You can access the private member that way, but if you had $class you should just make MyFunction a method of the class, as you would just call $class->MyFunction(). However you could have a static array that each instance is added to in the class constructor which this static function could access and iterate through, updating all the instances. ie..

class MyClass
{
  private $MyMember;
  private static $MyClasses;

  public function __construct()
  {
    MyClass::$MyClasses[] = $this;
  }

  public static function MyFunction()
  {
    foreach(MyClass::$MyClasses as $class)
    {
      $class->MyMember = 0;
    }
  }
}

class MyClass
{
  private static $MyMember = 99;

  public static function MyFunction()
  {
    echo self::$MyMember;
  }
}

MyClass::MyFunction();

see Visibility and Scope Resolution Operator (::) in the oop5 chapter of the php manual.


Within static methods, you can't call variable using $this because static methods are called outside an "instance context".

It is clearly stated in the PHP doc.


<?php
    class MyClass
    {
        // A)
        // private $MyMember = 0;

        // B)
        private static $MyMember = 0;

        public static function MyFunction()
        {
            // using A) //  Fatal error: Access to undeclared static property: 
            //              MyClass::$MyMember
            // echo MyClass::$MyMember; 

            // using A) // Fatal error: Using $this when not in object context
            // echo $this->MyMember; 

            // using A) or B)
            // echo $MyMember; // local scope

            // correct, B) 
            echo MyClass::$MyMember;
        }
    }

    $m = new MyClass;
    echo $m->MyFunction();
    // or better ...
    MyClass::MyFunction(); 

?>