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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php class Test { static $count = 18; public function getCount() { return self::$count; } public function showCount() { print self::getCount(); } } Test::showCount(); $test = new Test; print $test->getCount(); ?> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php class Test { static $count = 18; private static function getCount() { return self::$count; } public static function showCount() { print self::getCount(); } } $test = new Test; $test->showCount(); ?> |
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.