Categories
PHP

OOP in PHP: Static and Non Static Scopes

Learned these things the hard way, sharing if anyone might find useful.

1) Every method except the magic methods (__construct(), __call(), __get() etc) has a static scope even if you don’t explicitly declare it static . So, public function getCount() is always available, both in static and object instances. But remember, while calling in a static function, using $this will cause a fatal error.

2) Static properties are available ALWAYS through the self:: scope. That means, you can access self::$count both from static and instance scopes. This is good for sharing data between object instances.

3) Even if you declare a method static, it is available from instance scope:

PS: $this is not available if you explicitly declare a method static

Rule of thumb: Every method has a static scope (but properties don’t). Static items are available always – they’re like global properties and remains static across objects. If you explicitly declare a method static, it’ll have a static scope regardless of whether called from an instance or called statically.