views:

326

answers:

3

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?

+7  A: 
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.

VolkerK
+1 - I Didn't know about self keyword. your code worked! thanks :)
Senthil
+3  A: 

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.

Arno
+1  A: 
<?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(); 

?>
The MYYN
Can you call `$m->MyFunction();` like that if the function is static?
Senthil
yes you can, but maybe you shouldn't since it obscures the fact, that the function is object-bound ..
The MYYN
Weird. I thought you can only call static functions by ClassName::FunctionName and not by instantiating. Anyway, I have this doubt -> If you declare the variable like in case A) and use it like `echo $MyMember`, it is not working for me. It shouldn't work right? I am unable to understand your comment - `//local` there.
Senthil
as far as i know, when you use "echo $MyMember;", it refers to the "local scope" (here, the function) of the variable, and since we haven't defined any "$MyMember" inside the function, this line yields "nothing" ...
The MYYN
oh! Since you didn't mention any fatal error or something, i thought it will work :D. +1 for taking time to explain all the cases :)
Senthil