In certain cases, it is better to approach methods and properties of a class without the need to create an object out of the class. This can be achieved by defining the methods and properties of a class as static. Even though the use of static methods and properties is considered a bad practice, there are cases in which their use is quite handy and justified. Static methods can be called directly – without creating an instance / object of the class first.
<?php class greeting { public static function welcome() { echo "Hello World!"; } } // Call static method greeting::welcome(); ?>
<?php class greeting { public static function welcome() { echo "Hello World!"; } public function __construct() { self::welcome(); } } new greeting(); ?>
<?php class A { public static function welcome() { echo "Hello World!"; } } class B { public function message() { A::welcome(); } } $obj = new B(); echo $obj->message(); ?>
<?php class domain { protected static function getWebsiteName() { return "W3Schools.com"; } } class domainW3 extends domain { public $websiteName; public function __construct() { $this->websiteName = parent::getWebsiteName(); } } $domainW3 = new domainW3; echo $domainW3->websiteName; ?>
<?php class pi { public static $value = 3.14159; } // Get static property echo pi::$value; ?>