PHP类的静态(static)方法和静态(static)变量使用介绍,学习php的朋友可以看下
在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::.. 的方法调用,如之前所述
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

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
What's New in Windows 11 KB5054979 & How to Fix Update Issues
3 weeks agoByDDD
How to fix KB5055523 fails to install in Windows 11?
2 weeks agoByDDD
InZoi: How To Apply To School And University
4 weeks agoByDDD
How to fix KB5055518 fails to install in Windows 10?
2 weeks agoByDDD
Roblox: Dead Rails – How To Summon And Defeat Nikola Tesla
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version

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