简体   繁体   中英

Access static property through static and non-static methods?

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM