PHP Static Methods & Properties
Samuel K.M
Posted on October 28, 2021
Static Methods
Static methods can be called directly - without creating an instance of the class first.
Static methods are declared with the static
keyword:
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method
greeting::welcome();
?>
A static method can be accessed from a method in the same class using the self keyword and double colon (::):
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
public function __construct() {
self::welcome();
}
}
new greeting();
?>
Static methods can also be called from methods in other classes. To do this, the static method should be public:
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
class SomeOtherClass {
public function message() {
greeting::welcome();
}
}
?>
To call a static method from a child class, use the parent
keyword inside the child class. Here, the static method can be public or protected.
<?php
class Name{
protected static function getName() {
return "Bazeng";
}
}
class SayName extends Name {
public $name;
public function __construct() {
$this->name= parent::getName();
}
}
$name= new SayName;
echo $name ->name;
?>
Static properties
Static properties are declared with the static keyword
they can be called directly - without creating an instance of a class.Example:
<?php
class Person{
public static $name = "Bazeng";
}
echo Person::$name;
To access a static property in a method in same class use self
<?php
class Person{
public static $name = "Bazeng";
public function sayName(){
echo self::$name;
}
}
$person = new Person();
$person->sayName();
To access a static property in a method in a parent class use parent
<?php
class Person{
public static $name = "Bazeng";
}
class SayName extends Person{
public function __construct(){
echo parent::$name;
}
}
$person = new SayName();
Posted on October 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.