PHP Static methods
- 2020年5月25日
- 技術情報
I will talk about static methods usages in php with some code samples. Lets get started.
Here is a sample, calling static function outside of the class.
1 2 3 4 5 6 7 8 9 10 |
<?php class welcome { public static function sayHi() { echo "Welcome!"; } } // we can like this -> className::methodName() welcome::sayHi(); ?> |
We can also call within the class like this using self::
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php class welcome { public static function sayHi() { echo "Welcome!"; } public function msg() { self::sayHi(); } } $hi = new welcome(); $hi->msg(); ?> |
You can also call static methods from another class like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php class welcome { public static function sayHi() { echo "Welcome!"; } } class anotherClass { public function msg() { welcome::sayHi(); } } $var = new anotherClass(); $var->msg(); ?> |
You can choose any ways depending upon the situations, the result will still be the same.
By Yuuma
yuuma at 2020年05月25日 11:00:23