Access to a 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 am trying to access this property inside all of its methods, I cannot understand the correct syntax.

What I have:

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

Can someone tell me the actual syntax for this?

+6
source share
2 answers

For static properties, use even inside a non-stationary function

 return self::$mode; 

The reason for this is that static ownership exists regardless of whether the object was created or not. Therefore, we simply use the same pre-existing property.

+16
source

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

 $myClass = new myClass(); echo $myClass::$mode; 

Not this way:

 echo $myClass::mode; 
+3
source

Source: https://habr.com/ru/post/910630/


All Articles