Table of Contents
static in php
Static variables
Static method
Home Backend Development PHP Tutorial static_PHP tutorial in php

static_PHP tutorial in php

Jul 13, 2016 am 10:14 AM

static in php


Static members are a type of class variable, which can be thought of as belonging to the entire class rather than to an instance of the class. Different from general instance variables, static members only retain one variable value, and this variable value is valid for all instances, that is, all instances share this member.

$this only represents the current instance of the class, while self:: represents the class itself. This operator cannot be used in code outside the class, and it cannot identify its position in the inheritance tree hierarchy. That is to say, when using the self scope in an extended class, self can call methods declared in the base class, but it always calls methods that have been overridden in the extended class. Unlike $this, when using static variables, you must add the $ symbol after the scope qualifier.

In the extended class, when the base class method is overridden, use the parent scope to call the method defined in the base class. Static members can also only belong to the parent class. If a member is declared in both the subclass and the parent class, you can also use parant:: to access the variables in the parent class in the subclass. In this case, the static members of the parent class and the static members of the subclass hold different values.

You can write the name of the class on the left side of the :: operator to statically access a member to avoid creating an instance of the class. Not only does it eliminate the need to instantiate a class, it is also more efficient because each instance of the class takes up a small portion of system resources.

When using the :: operator to access member variables, you need to pay attention to the use of the $ symbol again. Because PHP currently does not support the use of dynamic static variables, that is to say, it does not support mutable static variables. When using $this->$var, the member being accessed is the value of the variable contained in $var. Instead of using the $ symbol to access a variable, you are actually looking for a constant of the class, and constants cannot be accessed through $this.

The static::scope proposed in PHP6 eliminates the need for us to use self:: and parent::. When you want to point to the final class that implements the function, you can use static::. This qualifier will calculate the members of the last class in the inheritance hierarchy immediately before the code is executed. One process is called lazy binding, which allows us to override a static variable in a child class and also access the final member from a function declared in the parent class.

Sometimes, it may be necessary to create fields and methods that are shared by all class instances, that are relevant to all class instances, but cannot be called by any specific object. For example, suppose you want to write a class that tracks the number of visitors to a web page. You definitely don’t want to reset the number of visitors to 0 every time you instantiate the class. At this time, you can set the field to static scope:

static_PHP tutorial in php
<?php
    class visitors
    {
        private static $visitors = 0;
        function __construct()
        {
             self::$visitors&#43;&#43;;
        }
        static function getVisitors()
        {
            return self::$visitors;
        }
    }
    /* Instantiate the visitors class. */
    $visits = new visitors();
    echo visitors::getVisitors()."<br />";
    /* Instantiate another visitors class. */
    $visits2 = new visitors();
    echo visitors::getVisitors()."<br />";
?>
Copy after login
static_PHP tutorial in php

Program execution result:

1

2

Because the $visitors field is declared static, any changes to its value will be reflected in all instantiated objects. Also note that static fields and methods should be referenced using the self keyword and class name, not via this and the arrow operator. This is because referencing static fields using "normal" methods is not possible and will result in syntax errors.

You cannot use $this in a class to refer to a static field.

Static variables

Static variables are variables that only exist in the scope of a function. However, the value of such a variable will not be lost after the function is executed. That is to say, the variable will still remember the original value the next time the function is called. . To define a variable as static, just add the static keyword before the variable.

In a class, the static keyword has two main uses, one is to define static members, and the other is to define static methods. Within a class, you can use the scope qualifier (::) to access variables at different levels of scope.

Static method

There is an important difference between static and non-static methods: when calling a static method, you no longer need to own an instance of the class.

Principles for using static methods and non-static methods: First, if a method does not contain the $this variable, it should be a static method; if you do not need an instance of the class, you may also use a static class, which can eliminate the need for an instance. Chemical work. In addition, the $this variable cannot be used in a static method, because the static method does not belong to a specific instance.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907370.htmlTechArticlestatic static member in php is a class variable, which can be regarded as belonging to the entire class rather than to the class an instance of . Different from general instance variables, static members only retain one...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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 debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

See all articles