How to Create and Use Static Classes in PHP
Kevin Amayi
Feb 02, 2024
- Create Static Class With Static Variables in PHP
- Create Static Class With Static Method in PHP
- Create Static Class and Call the Static Method on Another Class in PHP
-
Create Static Class and Call the Static Method on a Child Class Using the
parent
Keyword
![How to Create and Use Static Classes in PHP](/img/PHP/feature-image---static-classes-in-php.webp)
In PHP, a static class is a class that is only instantiated once in a program. It must have a static member (variable
), static member function (method
), or both.
Create Static Class With Static Variables in PHP
Let’s create a class
and initialize four
variables. We will then access them using the class name.
<?php
class Person {
//intialize static variable
public static $name = "Kevin";
public static $age = 23;
public static $hobby = "soccer";
public static $books = "HistoryBooks";
}
// print the static variables
echo Person::$name .'<br>';
echo Person::$age .'<br>';
echo Person::$hobby .'<br>';
echo Person::$books .'<br>';
?>
Output:
Kevin
23
soccer
HistoryBooks
Create Static Class With Static Method in PHP
We will initialize a method called simpleProfile()
. Then call the method using the class name.
<?php
class Person {
public static function simpleProfile() {
echo "I am a programmer and loves reading historical books.";
}
}
// Call static method
Person::simpleProfile();
?>
Output:
I am a programmer and loves reading historical books.
Create Static Class and Call the Static Method on Another Class in PHP
We call the swahiliMan()
method on another class using the class name
.
<?php
class greetings {
public static function swahiliGreeting() {
echo "Habari Yako!";
}
}
class swahiliMan {
public function greetings() {
greetings::swahiliGreeting();
}
}
$swahiliman1 = new swahiliMan();
$swahiliman1->greetings();
?>
Output:
Habari Yako!
Create Static Class and Call the Static Method on a Child Class Using the parent
Keyword
We instantiate a method with the static variable. After that, call the method using the parent
keyword and assign it to a variable on a child class that extends the static class.
class Person {
protected static function getCountry() {
return "Australia";
}
}
// a child class, extends the Person class
class Student extends Person {
public $country;
public function __construct() {
$this->country = parent::getCountry();
}
}
$student = new Student;
echo $student -> country;
?>
Output:
Australia