


Detailed explanation of the Static keyword in object-oriented PHP (code example)
Objectives of this article:
1. Understand the definition and function of static
2. Master the usage and characteristics of static
us To learn a piece of knowledge, you can learn it based on the ideas of 3w1h. Let’s briefly introduce 3w1h
3w1h that is
● what (what)
● why (why use it , what is its function)
● where (usage scenario)
● how (specifically how to use)
(1) Definition of static keyword (what)
1. Properties or methods modified by static are called static members of the class
(2) The role of the static keyword (why)
1. Let all instances of a class share a certain attribute or method.
(3). Static usage scenarios (where)
1. When you want a certain method or attribute to be When shared by all instances, you can consider static
(4), detailed use of static (how)
Summary:
1. Static To define an attribute, add static directly before the attribute definition, such as static public $name ;
2. Static attributes cannot be obtained by instances of classes, but can be obtained in the following ways:
● Class Name::$Attribute name
● Inside the class, you can pass self::$Attribute name
3. To define a static method, add static directly before the method definition, such as static public function Hello(){ }
4. Static methods cannot be obtained using class instances, but can be obtained in the following ways:
● Class name::Method name
● Inside the class, you can use self::method name
5. In PHP, you cannot use static to modify the class, you can only modify the properties or methods
6. Inside the static method Non-static properties cannot be called, only static properties
7. Non-static methods cannot be called inside static methods, only static methods
8. Non-static methods can be called inside non-static methods Static properties can also be called static properties
9. Within non-static methods, both non-static methods and static methods can be called
All the summaries are based on practice Come, then next, we use actual code to demonstrate each summary above to see if they are correct
(4), specific code
Case 1:
Practical goals:
1. To define static attributes, add static directly before the attribute definition, such as static public $name;
2. Static attributes cannot use classes Instead of obtaining the instance of
The running result is: Case 2:1. Static method Definition, add static directly before the method definition, such as static public function Hello(){ }
2. Static methods cannot be obtained using instances of the class, but can be obtained in the following ways: ● Class name:: Method name● Inside the class, you can pass self:: Method name
<?php class Human{ static public $name = "人类";//静态属性的定义 public function say(){ echo "self::name = ".self::$name ."<br/>"; } } //输出静态属性 echo "名称为:".Human::$name."<br/>"; $human = new Human(); $human->say(); ?>
and the result is:
1. In PHP, you cannot use static to modify classes, only properties or methods
<?php class Human{ public function __construct(){ self::staticFun1(); } static public function staticFun1(){ echo "我是静态方法<br/>"; } } //输出静态方法 Human::staticFun1(); //运行构造函数,看是否可以被正常调用 $human = new Human(); ?>The running result is: Parse error: syntax error, unexpected 'class' (T_CLASS), expecting :: (T_PAAMAYIM_NEKUDOTAYIM) in D:\E-class\class-code\classing\index. php on line 2
Case 4:
Practical goal:1. Non-static properties cannot be called inside static methods, only static properties can be called
<?php static class Human{ } ?>The running result is: Static attribute-humanFatal error: Uncaught Error: Using $this when not in object context in D:\E-class\class -code\classing\index.php:8 Stack trace: #0 D:\E-class\class-code\classing\index.php(18): Human::staticFun1() #1 {main} thrown in D: \E-class\class-code\classing\index.php on line 8
Case 5:
1. Static Non-static methods cannot be called inside the method, only static methods
<?php class Human{ static public $staticName = "静态属性-人类"; public $commonName="非静态属性-人类"; //定义静态方法 静态方法调用非静态属性 static public function staticFun1(){ echo $this->commonName."<br/>"; } //测试静态方法调用静态属性 static public function staticFun2(){ echo self::$staticName."<br/>"; } } Human::staticFun2();//OK Human::staticFun1();//not OK ?>The running result is:
I am a static method 2
Fatal error: Uncaught Error: Using $this when not in object context in D:\E-class\class-code\classing\index.php:8 Stack trace: #0 D:\E-class\class-code\classing\index.php(20): Human::staticFun1() #1 {main} thrown in D:\E-class\class-code\classing\index.php on line 8
案例六:
实践目标:
1、非静态方法内部,既可以调用非静态属性也可以调用静态属性
<?php class Human{ static public $staticName = "静态属性-人类"; public $name = "非静态属性-人类"; ///普通方法 public function commonFun1(){ echo self::$staticName."<br/>"; echo $this->name."<br/>"; } } $human = new Human(); $human->commonFun1(); ?>
运行结果为:
静态属性-人类
非静态属性-人类
案例七:
实践目标:
1、非静态方法内部,既可以调用非静态方法也可以调用静态方法
<?php class Human{ ///普通方法 public function commonFun1(){ self::staticFun1(); $this->commonFun2(); } //测试静态方法调用 静态方法 static public function staticFun1(){ echo "我是静态方法1<br/>"; } public function commonFun2(){ echo "我是普通方法2<br/>"; } } $human = new Human(); $human->commonFun1(); ?>
运行结果为:
我是静态方法1
我是普通方法2
(五)、学以致用
问题:
1、所有的NBA球员都有一个共同的联盟总裁,David Stern(大卫*斯特恩)
2、总裁换成了“Adam Silver” 怎么办?
大家自己思考一下,再看后面的结果
.........................
答案揭晓:
思路分析:
1、“换”是一个动词,换总裁,所以是一个方法,而总裁是一个数据,所以是一个属性
2、换总裁要达到一个目的就是,换了以后,这个对象仍然要被其他所有的NBA球员对象使用到
3、既然 总裁 (属性) 要被所有的NBA球员对象 共享,那么我们就可以结合static的作用,将总裁属性定义为静态属性
4、所以根据综上所述,大概的思路就是定义一个NBA球员类,然后类里面主要有静态属性“总裁”和一个 换总裁 的方法
具体代码如下:
<?php //Nba球员类 class NbaPlayer{ public $name = ""; //构造函数初始化对象 public function __construct($name){ $this->name = $name; } //总裁 static public $president = "David Stern"; //换总裁方法 public function changePresident($name){ self::$president = $name; } } $jordon = new NbaPlayer("乔丹"); $kebo = new NbaPlayer("科比"); echo "输出他们目前共同的总裁,总裁为:".NbaPlayer::$president."<br/>"; echo "现在把乔丹总裁换成Adam Silver<br/>"; $jordon->changePresident("Adam Silver"); echo "输出科比的总裁是否也和乔丹的一样,科比总裁为:".NbaPlayer::$president."<br/>"; ?>
运行结果为:
输出他们目前共同的总裁,总裁为:David Stern
现在把乔丹总裁换成Adam Silver
输出科比的总裁是否也和乔丹的一样,科比总裁为:Adam Silver
总结:
1、本文主要是讲了static关键字的定义和特点
希望本文能给大家带来一定的帮助,谢谢!!!
The above is the detailed content of Detailed explanation of the Static keyword in object-oriented PHP (code example). For more information, please follow other related articles on the PHP Chinese website!

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.


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

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

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.
