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?
Static Methods can access static variables without any objects, however non-static methods and non-static variables can only be accessed using objects. Static methods can be accessed directly in static and non-static methods.
Static method uses complie time binding or early binding. Non-static method uses run time binding or dynamic binding. A static method cannot be overridden being compile time binding. A non-static method can be overridden being dynamic binding.
You have to create instance first. The instance method (method that is not static) cannot be accessed from static context by definition. Show activity on this post. Basically, you can only call non-static methods from objects [instances of a class] rather than the class itself.
Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ). print $foo::$my_static .
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With