Access static property through static and non-static methods?

24,252

Solution 1

For static properties use the following even inside a non static function

return self::$mode;

The reason for this is because the static propery exists whether an object has been instantiated or not. Therefore we are just using that same pre-existing property.

Solution 2

If you are outside of the class, make sure not to forget the $ or you will see this error as well. For example, make sure to call it like this:

$myClass = new myClass();

echo $myClass::$mode;

Not like this:

echo $myClass::mode;
Share:
24,252
DanRedux
Author by

DanRedux

Working as a Programmer, mostly designing custom apps in PHP. Also tutoring, mostly High School Math/Game Design.

Updated on August 31, 2020

Comments

  • DanRedux
    DanRedux over 3 years

    I have a class and it has some static, some not static methods. It has a static property. I'm trying to access that property inside all of it's methods, I can't figure out the right syntax.

    What I have is this:

    class myClass {
        static public $mode = 'write';
        static public function getMode() {
            return myClass::$mode; 
        }
        public function getThisMode() {
            return $this->mode;
        }
    }
    

    Can anyone tell me the actual syntax for this one?

  • DanRedux
    DanRedux about 12 years
    Yep, that worked. Thanks. I'm a little curious why className::$mode doesn't work, though? I'll accept your question as soon as it let's me.
  • yehuda
    yehuda about 12 years
    @DanRedux Cheers. Are you sure your first function does not return anything?
  • yehuda
    yehuda about 12 years
    @DanRedux just checked your code and both work fine with my change of self. using myClass is just fine too.
  • santiago arizti
    santiago arizti over 6 years
    if the class is extedned with a child class, then it is best to use static::$mode so the child class inherits the correct behaviour of the method