How to use the static keyword in PHP?

by elisha_langworth , in category: PHP General , a year ago

How to use the static keyword in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by filiberto , a year 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->.

Member

by mac , 3 months ago

@elisha_langworth 

Using the static keyword allows us to share a variable or method a**** all instances of a class, without having to create separate copies of it for each instance. This can be useful when we want to keep track of a common value or when we want to perform an action that is not specific to a particular instance of the class.