Understanding Static Members in PHP
In PHP, static members (methods and properties) belong to the class itself, not to individual objects. This means you can access them without creating an instance of the class. Static members are useful when you want to share data or functionality across multiple objects. PHP provides three keywords to access static methods and properties: self::, parent::, and static::. Each works differently, especially when using inheritance. In this article, we’ll explain how these keywords work and show their differences with examples.
When to Use Static Members
Global Variables: Static properties can be used as global variables within a class, accessible to all instances.
Utility Methods: Static methods can provide utility functions that are independent of individual objects.
Class-Level Constants: Static properties can be used to define class-level constants.
Singleton Pattern: Static methods and properties are essential for implementing the Singleton pattern.
Calling Static Methods
To call a static method, you use the :: operator followed by the method name. Here's an example:
class MyClass { public static function greet() { echo "Hello, world!"; } } MyClass::greet(); // Output: Hello, world!
Calling Static Properties
To access a static property, you also use the :: operator followed by the property name. Here's an example:
class MyClass { public static $count = 0; public static function incrementCount() { self::$count++; } } MyClass::incrementCount(); echo MyClass::$count; // Output: 1
The Three Keywords: self::, parent::, and static::
self::
The self:: keyword refers to the class in which the code is written. It does not account for inheritance, meaning if a child class overrides a static method or property, self:: will still refer to the parent class where the code is defined.parent::
The parent:: keyword is used to call a static method or property from the immediate parent class. It bypasses any overridden methods in the child class, ensuring that the parent’s method or property is used.static::
The static:: keyword works similarly to self::, but it accounts for late static binding. This means that if a static method or property is overridden in a child class, static:: will refer to the method or property in the most derived class, even if it's called from a parent class.
Examples to Show the Differences
Let’s see how each of these keywords behaves in a PHP program with inheritance.
Example 1: Using self::
class A { public static function sayHello() { return "Hello from A"; } public static function test() { return self::sayHello(); } } class B extends A { public static function sayHello() { return "Hello from B"; } } echo B::test(); // Output: "Hello from A"
In this example, self:: in class A refers to the sayHello() method in A. Even though class B overrides the method, self:: calls the parent class method, producing the output "Hello from A."
Example 2: Using parent::
class A { public static function sayHello() { return "Hello from A"; } } class B extends A { public static function sayHello() { return parent::sayHello() . " and B"; } } echo B::sayHello(); // Output: "Hello from A and B"
In this example, class B calls parent::sayHello() to include the message from the parent class A and then appends its own message. The output is "Hello from A and B."
Example 3: Using static::
class A { public static function sayHello() { return "Hello from A"; } public static function test() { return static::sayHello(); } } class B extends A { public static function sayHello() { return "Hello from B"; } } echo B::test(); // Output: "Hello from B"
Here, static:: in class A refers to the method sayHello() in the most derived class, which is B. This is because static:: allows late static binding, and the method in class B is called, resulting in "Hello from B."
Key Differences
self::: Refers to the class in which it is used, ignoring inheritance. This is useful when you don’t want methods in child classes to affect the method being called.
parent::: Specifically calls methods or properties from the parent class, even if they are overridden in the child class. It’s useful when extending functionality from a parent class but still needing access to the original methods.
static::: Enables late static binding, meaning it refers to the method or property in the most derived class at runtime, even if called from a parent class. It’s useful for situations where you want the behavior to adapt depending on the calling class.
Understanding the differences between self::, parent::, and static:: helps write more robust, maintainable PHP code, especially in complex object-oriented systems.
The above is the detailed content of Understanding Static Members in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
