How to use the static keyword in PHP?

by elisha_langworth , in category: PHP General , 6 months ago

How to use the static keyword in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 6 months ago

@elisha_langworth 

In PHP, the static keyword is used to declare class-level variables and methods. When a variable or method is declared as static, it belongs to the class rather than to an instance of the class.


Here's an example of how to use the static keyword in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class MyClass {
    public static $count = 0;

    public static function incrementCount() {
        self::$count++;
    }

    public function getCount() {
        return self::$count;
    }
}

MyClass::incrementCount();
echo MyClass::$count; // Output: 1

$obj = new MyClass();
$obj->incrementCount();
echo $obj->getCount(); // Output: 2


In this example, we declare a static variable $count and a static method incrementCount() in the MyClass class. The incrementCount() method increments the $count variable by one.


We can access the static variable and method using the class name, as shown in the echo statements. We can also access them through an instance of the class, as shown in the second echo statement.


Note that when accessing a static variable or method within the class, we use self:: instead of $this->.