PHP类的静态(static)方法和静态(static)变量,phpstatic
在php中,访问类的方法/变量有两种方法:
1. 创建对象$object = new Class(),然后使用”->”调用:$object->attribute/function,前提是该变量/方法可访问。
2. 直接调用类方法/变量:class::attribute/function,无论是静态/非静态都可以。但是有前提条件:
A. 如果是变量,需要该变量可访问。
B. 如果是方法,除了该方法可访问外,还需要满足:
b1) 如果是静态方法,没有特殊条件;
b2) 如果是非静态方法,需要改方法中没有使用$this,即没有调用非静态的变量/方法,当然,调用静态的变量/方法没有问题。
然后我们再看一下使用$object->… 和使用class::… 都有什么区别:
1. 使用$object->… ,需要执行构造函数创建对象;
2. 使用class::… 调用静态方法/变量,不需要执行构造函数创建对象;
3. 使用class::… 调用非静态方法/变量,也不需要执行构造函数创建对象。
然后奇怪的地方就出来了,既然2和3都一样,那静态方法/变量存在还有什么意义呢?
差异还是显然存在的,如下:
1. 静态变量
静态成员只保留一个变量值,而这个变量值对所有的实例都是有效,也就是说,所有的实例共享这个成员。
2. 静态方法
静态方法可以直接使用class::… 来调用,而非静态方法需要满足一定限制条件才能使用class::.. 的方法调用,如之前所述

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

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.

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.

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment