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

anon355079 picture anon355079 · Dec 24, 2009 · Viewed 34k times · Source

I have the following class in PHP

class MyClass
{
  // How to declare MyMember here? It needs to be private
  public static function MyFunction()
  {
    // How to access MyMember here?
  }
}

I am totally confused about which syntax to use

$MyMember = 0; and echo $MyMember

or

private $MyMember = 0; and echo $MyMember

or

$this->MyMember = 0; and echo $this->MyMember

Can someone tell me how to do it?

I am kind of not strong in OOPS.

Can you do it in the first place?

If not, how should I declare the member so that I can access it inside static functions?

Answer

VolkerK picture VolkerK · Dec 24, 2009
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.