1. Code
  2. Coding Fundamentals
  3. OOP

Understanding Static Functions and Static Classes in PHP

Scroll to top
5 min read
14

Static functions and static classes can be easily accessed without necessarily creating an instance of that class. This helps keep your code clean and organized.

In this post, you'll learn about the static keyword and how it is applied to functions and classes to make them static. Then, I'll explain why you might want to implement static functions and classes in PHP.

By the end, you'll understand how to make functions and variables within a class static, how to access these static members, and when to declare class members as static.

Using the static Keyword With a Method or Variable

static is a special keyword in PHP. Where it is used on methods or class properties, it allows them to be accessed on the class itself instead of on an instance of that particular class. So instead of writing:

1
$object = new MyClass();
2
$object.someMethod();

We can write:

1
MyClass::someStaticMethod();

Therefore, whenever a method is declared as static, it can easily be accessed without the need to create an object for the class.

Of course, this only works for methods that don't need to use any data from the instances of a class. Declaring a method as static limits it to accessing static methods and static variables.

Declaring a Static Function and a Static Variable

The code below declares a function named newFunction as static by adding the static keyword before the function’s name. A property named design_name is also made static by including the static keyword before its name. When referencing the property within the static function, the scope resolution operator :: and the self keyword are used.

It is impossible for a static method to access a non-static variable or non-static methods because these require an instance of the class to be created.

1
<?php
2
class SomeClass {
3
    //Declaring a static variable

4
    public static $design_name = 'Kimono World';
5
6
    //Declaring a static function

7
    public static function newFunction() {
8
    echo self::$design_name;
9
    }
10
}
11
12
SomeClass::newFunction()
13
?>

The output for the above code snippet would be:

1
Kimono World

However, a static method can be accessed by a non-static method within the same class by the use of self:::

1
<?php
2
class regards {
3
    public static function greetings(){
4
        echo 'Hola!';
5
    }
6
    public function __construct(){
7
//accessing the greetings static function through the construct() non-static method

8
       self::greetings();
9
    }   
10
}
11
new regards();
12
13
?>

When you create a new instance of the class, the constructor will call the static function and output Hola!.

You can also access a static method in one class from another class by making the static method public.

1
<?php
2
class FirstClass {
3
    public static function firstFunction(){
4
        echo 'Let’s see how this works';
5
    }
6
}
7
class SecondClass{
8
    public function functionTwo(){
9
       FirstClass::firstFunction();
10
    }
11
}
12
13
$class1 = new SecondClass;
14
echo $class1 -> functionTwo();
15
?>

This code will output:

1
Let’s see how this works

A static method can also be called from a child class (the concept of inheritance) by using the parent keyword within the child class. In this case, the static method could either be public or protected.

If you want to use a static method within subclasses, but not from outside the class, you can declare the method with the protected keyword.

1
<?php
2
class address {
3
    protected static function retrieveIPAddress() {
4
        return '197.254.48.214';
5
    }
6
}
7
class address2 extends address {
8
    public $IPAddress;
9
    public function __construct(){
10
        $this->IPAddress = parent::retrieveIPAddress();
11
    }
12
}
13
$address2 = new address2;
14
echo $address2 -> IPAddress;
15
16
?>

In the code snippet above, the child class—address2—inherits from the parent class address. In the child class is a publicly declared variable that is accessed within the non-static constructor method __construct(). The static method retrieveIPAddress is then accessed with parent::retrieveIPAddress. The IP address is returned as the output.

Static Classes

Basically, a class is an independent and self-contained data type that can contain data members called properties and member functions which can only be accessed by initializing an instance of that class.

Declaring a class as static allows the values it holds to remain the same for every instance of that class. A non-static class, on the other hand, can have different property values for each instance.

How to Create a Static Class

A class becomes static when the variables and methods defined within it are made static using the static keyword.

A static class and its defined static method(s) can be accessed by using the class name, the :: (scope resolution) operator, and the method name, as displayed in the snippet below.

1
name_of_class::name_of_method();
1
<?php
2
class Student 
3
{
4
public $school;
5
public $course;
6
public static $registrationNumberLength = 13;
7
 
8
public function Details()
9
{
10
    return $this->course . 'course belongs to the school of' . $this->school;
11
}
12
public static function verifyRegNumber($registrationNumber)
13
{
14
    if (strlen($registrationNumber) >= self::$registrationNumberLength)
15
        return true;
16
    else
17
        return false;
18
}
19
}
20
21
$registrationNumber = 'J17/0798/201';
22
if (Student::VerifyRegNumber($registrationNumber))
23
    echo 'Registration Number length is correct';
24
else
25
    echo 'Registration Number length is invalid';
26
27
?>

In the above program, we have made both the $registrationNumberLength variable and the verifyRegNumber() function static. Remember, you can only access static variables from static functions, and that way we will not have to instantiate the class at any point. It actually is so much easier to work with the variables and the functions statically in the sense that a general functionality is provided and the information used is not specific to the one student. Notice that when accessing the $course and $school variables, which are non-static, we returned them by using the this keyword and the -> arrow to imply that they are instances of the Student class.

So basically, the main difference between static members and the normal classes, methods, and variables when they are being accessed is the use of the double colon :: instead of the -> arrow operator.

Conclusion

In this article, you learned how to use static functions and static classes, and hopefully got interested in learning more about these concepts in the future. The static concept in PHP, and everything regarding it, should be clearer than ever now! Happy coding!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.