PHP Static

PHP Static

Last Updated on Mar 22, 2023

Introduction

Till now whenever we wanted to call a function inside a class we created a new instance(object) of that class and then called the method. Like this:

Class Human {
    private $name = 'Human';
    public function sayHello(){
        echo 'Hello World! My name is '. $this->name;
    }
}

$human = new Human();
$human->sayHello();

What if we don’t want to create an instance everytime we want to call a function of a class? Then we can use static methods and properties.

Static

Inside the class we define the function as static

public static function sayHello(){
        
}

Then when we want to call it, we use :: rather than -> and there is no need to instantiate the class.

So rather than

$human = new Human();
$human->sayHello();

We write

Human::sayHello();

$this vs self

Inside the static class if you want to get the value of property you can’t use $this keyword anymore. You should use self and rather than -> you should use :: and make sure the property itslef is also static

private static $name = 'Static Human';
public static function sayHello(){
        echo 'Hello World! My name is '. self::$name;
}

So let’s see both of the static and non-static next to each other:

Class Human {
    private $name = 'Human';
    public function sayHello(){
        echo 'Hello World! My name is '. $this->name;
    }
}
$human = new Human();
$human->sayHello();

Class StaticHuman {
    private static $name = 'Static Human';
    public static function sayHello(){
        echo 'Hello World! My name is '. self::$name;
    }
}
StaticHuman::sayHello();
https://youtu.be/1PcMAzliHV0

Conclusion

Now you know about static methods and properties in PHP.

I recommend you to open a PHP files and define static methods and properties for your class and then try to access them.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • static methods
  • static properties

Category: programming

Tags: #php #oop

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses