Access static property through static and non-static methods?
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;
DanRedux
Working as a Programmer, mostly designing custom apps in PHP. Also tutoring, mostly High School Math/Game Design.
Updated on August 31, 2020Comments
-
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 about 12 yearsYep, 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 about 12 years@DanRedux Cheers. Are you sure your first function does not return anything?
-
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 over 6 yearsif 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