search
HomeBackend DevelopmentPHP TutorialUnderstanding the static keyword in php

Understanding the static keyword in php

Nov 26, 2019 pm 05:35 PM
phpstatic

Understanding the static keyword in php

Understanding of the static keyword in php

Understanding of static static variables

The static variable type specifier is static.

Static variables belong to the static storage method, and their storage space is the static data area in the memory (storage units are allocated in the static storage area). The data in this area occupies these storage spaces throughout the running of the program. (It is not released during the entire running of the program), and it can also be considered that its memory address remains unchanged until the end of the entire program (on the contrary, auto automatic variables, that is, dynamic local variables, belong to the dynamic storage category and occupy dynamic storage space. Functions Released after the call is completed). Although static variables always exist throughout the execution of the program, they cannot be used outside its scope.

In addition, quantities belonging to static storage methods are not necessarily static variables. For example: Although external variables belong to the static storage method, they are not necessarily static variables. They must be defined by static before they can become static external variables, or static global variables.

All global variables are static variables, and local variables are local static variables only when they are defined with the type modifier static.

Static variables can be applied anywhere. Once the application is successful, it will no longer accept other similar applications.

Static variables do not mean that they cannot change the value. A quantity that cannot change the value is called a constant. The value it holds is mutable, and it will remain up-to-date. It is said to be static because it does not change when the function is called or exits. That is, if we assign a certain value to a static variable the last time the function is called, the value will remain unchanged the next time the function is called.

Static variables within the function

static usage

1, please see the following example:

function doStuff(&$cache) {
    static $cache = null;
    if ($cache === null) {
        echo $cache = '%heavy database stuff or something%';
    }
}
$cache = 'not null';
doStuff($cache);
// Output
%heavy database stuff or something%

And, in doStuff( ) function, the static variable $cache is not immutable, $cache changed from null to %heavy database stuff or something%; from the above example, we can see that the static keyword affects reference transfer, even if we use & To try to change the value and address of the variable $cache, it still does not affect the if judgment in the doStuff() function;

Static methods and attributes in the class

● We Treat the class as a template for generating objects, use the object as an active component, instantiate a class, get an object, and then access the methods and properties of the object.

For example $foo = new Foo(); $foo is the object after instantiation of class Foo.

● Static methods are functions with class as scope. We can directly access static methods without instantiation.

For example:

class Foo()
{
    public static function a(){}
}
// 访问a();
Foo::a();

● In the current class ( To access static methods or attributes in non-subclasses) use self::method(), note: self can call static methods and attributes of the parent class; ● Static methods cannot access ordinary attributes and methods in this class, because those attributes and methods Belonging to an object, static methods and properties are also called methods of class variables.

Delayed static binding

Let’s look at an example first

header("Content-type: text/html; charset=utf-8");
class A
{
    public static function aa()
    {
        echo "非延迟静态绑定<br>";
    }
     
    public static function bb()
    {
        echo self::aa();  // Output 非延迟静态绑定
        echo static::aa(); // Output 延迟静态绑定
    }
}
class B extends A
{
    public static function aa()
    {
        echo "延迟静态绑定";
    }
     
    public static function cc()
    {
        echo self::bb();
    }
}
B::bb();
// Output
非延迟静态绑定
延迟静态绑定

After php5.3, we can use static to get the aa() of the subclass Method, which refers to the class being called. Using the self keyword refers to the current class (A), so what is obtained is the return value of the aa() method of class A;

Summary:

Lazy binding of the static keyword It has many uses and can generally be summarized while working on a project.

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of Understanding the static keyword in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Laravel routing parameter delivery and controller method definition: Avoiding common errors and best practicesLaravel routing parameter delivery and controller method definition: Avoiding common errors and best practicesJul 23, 2025 pm 07:27 PM

This tutorial details the correct method of parameter passing in Laravel routing, and corrects common errors in writing parameter placeholders into controller method names. The article provides examples of standardized routing definitions and controller methods, and emphasizes that deletion operations should prioritize the use of HTTPDELETE methods to enhance routing semantics and maintainability.

Guide to matching Laravel routing parameter passing and controller methodGuide to matching Laravel routing parameter passing and controller methodJul 23, 2025 pm 07:24 PM

This article aims to resolve common errors in the Laravel framework where routing parameter passing matches controller methods. We will explain in detail why writing parameters directly to the controller method name in the routing definition will result in an error of "the method does not exist", and provide the correct routing definition syntax to ensure that the controller can correctly receive and process routing parameters. In addition, the article will explore best practices for using HTTPDELETE methods in deletion operations.

How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization modelHow to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization modelJul 23, 2025 pm 07:21 PM

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

Efficiently use JSON data to implement cascading drop-down menus in Laravel Blade templatesEfficiently use JSON data to implement cascading drop-down menus in Laravel Blade templatesJul 23, 2025 pm 07:18 PM

This article details how to load a local JSON file in a Laravel application and pass its data to a Blade template. By processing JSON parsing by the controller, the view layer uses Blade's @foreach instruction to traverse the data, thereby realizing dynamically generating drop-down menus. In particular, the article also explores in-depth how to combine JavaScript to implement multi-level linkage drop-down menu functions to provide users with dynamic content display based on selection, and provides practical code examples and precautions for implementing such interactions.

Deep analysis of matching Laravel routing parameter transfer and controller methodDeep analysis of matching Laravel routing parameter transfer and controller methodJul 23, 2025 pm 07:15 PM

This article deeply explores the correct transmission of routing parameters and the matching mechanism of controller methods in the Laravel framework. In response to the common "method does not exist" error caused by writing routing parameters directly to the controller method name, the article elaborates on the correct way to define routing, that is, declare parameters in the URI and receive them as independent parameters in the controller method. At the same time, the article also provides code examples and suggestions on best practices for HTTP methods, aiming to help developers build more robust and RESTful Laravel applications.

PHP integrated AI intelligent image processing PHP image beautification and automatic editingPHP integrated AI intelligent image processing PHP image beautification and automatic editingJul 23, 2025 pm 07:12 PM

PHP integrated AI image processing requires the help of a third-party API or local model, which cannot be directly implemented; 2. Use ready-made services such as Google CloudVision API to quickly realize facial recognition, object detection and other functions. The advantages are fast development and strong functions. The disadvantages are that they need to pay, rely on the network and have data security risks; 3. Deploy local AI models through PHP image library such as Imagick or GD combined with TensorFlowLite or ONNXRuntime. It can be customized, the data is safer, and the cost is low, but the development is difficult and requires AI knowledge; 4. Mixed solutions can combine the advantages of API and local model, such as using API for detection and beautification of local models; 5. Selecting AI image processing API should be comprehensive

Twilio Voice Call Maintenance and Recovery: Meeting Functions and Independent Call Leg Management PracticeTwilio Voice Call Maintenance and Recovery: Meeting Functions and Independent Call Leg Management PracticeJul 23, 2025 pm 07:09 PM

This article discusses in-depth two main strategies for realizing voice call holding (Hold) and recovery (Unhold) on the Twilio platform. First, we introduce the detailed introduction to leveraging the Twilio Conference feature to easily manage call retention by updating the Participant resources, and provide corresponding code examples. Second, for scenarios where more detailed control of independent call legs (CallLeg) is required, how to combine TwiML instructions (such as and/) to handle call reconnection, while highlighting the complexity of this approach. The article aims to provide professional and practical guidance to help developers choose the most suitable implementation solution according to specific needs.

Laravel routing parameter passing: correctly define the controller method and routing bindingLaravel routing parameter passing: correctly define the controller method and routing bindingJul 23, 2025 pm 07:06 PM

This article discusses the correct posture of parameter transfer of controller method in Laravel routing in depth. In response to common errors caused by writing routing parameters directly to the controller method name, the correct routing definition syntax is explained in detail, and the mechanism of Laravel automatic parameter binding is emphasized. At the same time, the article recommends using HTTPDELETE method that is more in line with RESTful specifications to handle deletion operations to improve the maintainability and semantics of the application.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.