Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access static property through static and non-static methods?

Tags:

oop

php

static

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?

like image 776
DanRedux Avatar asked Mar 13 '12 19:03

DanRedux


People also ask

Which method can be accessed directly in static and non static methods?

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.

What is the difference between 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.

How do you access a non static method from a static context?

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.

How do you access static properties?

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 .


1 Answers

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.

like image 118
yehuda Avatar answered Oct 05 '22 03:10

yehuda