search
HomeBackend DevelopmentPHP Tutorialstatic_PHP tutorial in php

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 />";
?>
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
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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version