php static The "static" in static methods means that these properties and methods can be called directly without instantiating the class; static is a keyword used to modify the properties and methods of the class. Its usage syntax is such as "class Foo {public static $my_static = 'hello';}".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
PHP static static detailed explanation
PHP class attributes and methods need to be called after the class is instantiated (except constant attributes), however, PHP also provides static attributes and static methods. The so-called "static" means that these properties and methods can be called directly without instantiating the class. It’s not that static classes cannot be instantiated, but they can be used without instantiation.
Definition of static members
Use the static keyword to modify the attributes and methods of the class, and call these attributes and methods static attributes and static methods.
1. Static attribute
Syntax:
static?屬性名
Example:
<?php class Foo { public static $my_static = 'hello'; } ?>
2. Static method
Syntax:
static?function?方法名{ ????//代碼 }
Example:
<?php class Foo { public static function staticValue() { return 'hello'; } } ?>
Note: Static properties and methods are the same as object properties and methods. They support setting private
, protected
, public
Three visibility levels.
Call of static members
1. Call static properties/methods outside the class
Pass class name::property/method
# Called in ## mode.
<?php class Mystatic { public static $staticvalue = 'zhangsan'; public static function staticMethod() { $a = 'hello'; return $a; } } echo '$staticvalue: '.Mystatic::$staticvalue.PHP_EOL; echo '$a: '.Mystatic::staticMethod().PHP_EOL; ?>Note: The predefined constant
PHP_EOL represents the system newline character.
$staticvalue:?zhangsan $a:?helloCalled by
Object name::Property/Method
.
<?php class Mystatic { public static $staticvalue = 'zhangsan'; public static function staticMethod() { $a = 'hello'; return $a; } } $obj = new Mystatic(); echo '$staticvalue: '.$obj::$staticvalue.PHP_EOL; echo '$a: '.$obj::staticMethod(); ?>Result:
$staticvalue:?zhangsan $a:?helloCalled by
object name-> method, object name-> attribute
will fail.
<?php error_reporting(0); class Mystatic { public static $staticvalue = 'zhangsan'; public static function staticMethod() { $a = 'hello'; return $a; } } $obj = new Mystatic(); echo '$staticvalue: '.$obj ->?staticvalue.PHP_EOL; echo?'$a:?'.$obj?->?staticMethod(); ?>Result:
$staticvalue: $a:?hello2. Call static properties/methods in non-static methods Pass
self::properties/methods
is called, self points to the current class, just like $this points to the current object; and in the absence of instantiation, $this The pointer points to an empty object
, so it cannot be touched to reference static properties and methods.
<?php class Mystatic { public static $staticvalue = 'zhangsan'; public static function staticMethod() { $a = 'hello'; return $a; } public function noStatic(){ echo '$staticvalue: '.self::$staticvalue.PHP_EOL; echo '$a: '.self::staticMethod(); } } $obj = new Mystatic(); $obj ->?noStatic(); ?>Result:
$staticvalue:?zhangsan $a:?hello3. Calling static properties/methods in static methods is the same as calling static properties/methods in non-static methods.
<?php class Mystatic { public static $staticvalue = 'zhangsan'; public static function staticMethod1() { $a = 'hello'; return $a; } public static function staticMethod2(){ echo '$staticvalue: '.self::$staticvalue.PHP_EOL; echo '$a: '.self::staticMethod1().PHP_EOL; } } Mystatic::staticMethod2(); $obj = new Mystatic(); $obj ->?staticMethod2(); ?>Result:
$staticvalue:?zhangsan $a:?hello $staticvalue:?zhangsan $a:?hello4. Call the static properties/methods of another classIf you call the static properties and methods of other classes in one class, you need to pass
Full class name:: for reference.
<?php class Mystatic1 { public static $staticvalue1 = 'xiaomin'; } class Mystatic2 { public static $staticvalue2 = 'zhangsan'; public static function staticMethod() { echo '$staticvalue1: '.Mystatic1::$staticvalue1.PHP_EOL; echo '$staticvalue2: '.self::$staticvalue2.PHP_EOL; } } Mystatic2::staticMethod(); $obj = new Mystatic2(); $obj ->?staticMethod(); ?>Result:
$staticvalue1:?xiaomin $staticvalue2:?zhangsan $staticvalue1:?xiaomin $staticvalue2:?zhangsan5. Call
private,
protected static properties/methods at visibility level
Due to# The ##private and protected
attributes are restricted to being called within the class. If you want to call it outside the class, you need to provide a public
method for the outside. The method accesses private
, protected
attributes. Terminology: A class provides an interface to the outside world. <pre class="brush:php;toolbar:false"><?php
class Mystatic {
public static $staticvalue1 = &#39;zhangsan&#39;;
private static $staticvalue2 = 20;
protected static $staticvalue3 = &#39;student&#39;;
private static function staticMethod() {
$a = &#39;hello&#39;;
return $a;
}
public function port1() {
echo &#39;$staticvalue1: &#39;.self::$staticvalue1.PHP_EOL;
echo &#39;$staticvalue2: &#39;.self::$staticvalue2.PHP_EOL;
echo &#39;$staticvalue3: &#39;.self::$staticvalue3.PHP_EOL;
echo &#39;$a: &#39;.self::staticMethod().PHP_EOL;
}
public static function port2() {
echo &#39;$staticvalue1: &#39;.self::$staticvalue1.PHP_EOL;
echo &#39;$staticvalue2: &#39;.self::$staticvalue2.PHP_EOL;
echo &#39;$staticvalue3: &#39;.self::$staticvalue3.PHP_EOL;
echo &#39;$a: &#39;.self::staticMethod().PHP_EOL;
}
}
$obj = new Mystatic();
$obj ->?port1();
echo?"\r\n";
Mystatic::port2();
?></pre>
Result:
$staticvalue1:?zhangsan $staticvalue2:?20 $staticvalue3:?student $a:?hello $staticvalue1:?zhangsan $staticvalue2:?20 $staticvalue3:?student $a:?hello
Static properties support dynamic modification
In actual applications, there will be multiple objects of a class, which may share a copy of data. Both class constants and static properties can be implemented. Static properties are similar (identical) to class constants, the only difference is that class constants cannot be changed, while static properties can be changed. The access method is the same and can be accessed using
::. Static properties need to add $, and there is no $ before the constant name, so there is no need to add it when accessing class constants. 1. Class constants
<?php class Myconst { const A = 1234; } $obj1 = new Myconst(); echo 'A: '.$obj1::A.PHP_EOL; $obj1->A='aaa'; //$obj1::A='aaa';會(huì)報(bào)錯(cuò) echo?"\r\n"; $obj2?=?new?Myconst(); echo?'A:?'.$obj2::A.PHP_EOL; ?>
Result:
A:?1234 A:?1234
2. Static attributes
<?php class Mystatic { public static $A = 1234; } echo '$A: '.Mystatic::$A.PHP_EOL; Mystatic::$A = 6666; echo '$A: '.Mystatic::$A.PHP_EOL; $obj1 = new Mystatic(); echo '$A: '.$obj1::$A.PHP_EOL; Mystatic::$A = 5555; $obj2 = new Mystatic(); echo '$A: '.$obj2::$A.PHP_EOL; echo '$A: '.$obj1::$A.PHP_EOL; ?>
Result:
$A:?1234 $A:?6666 $A:?6666 $A:?5555 $A:?5555
Inheritance of static members Like overriding
and non-static properties/methods, static properties and methods can also be inherited by subclasses, and static properties and methods can also be overridden by subclasses.
1. Static attributes
Subclasses can override the static member variables of the parent class, but the static variables of the parent class still exist. These two static member variables are independent. They will be called according to the call The class names are accessed separately.
<?php class Mystatic { static public $a; //定義一個(gè)靜態(tài)變量 static function test() //定義靜態(tài)方法來操作并輸出靜態(tài)變量 { self::$a++; return self::$a; } } class Mystatic2 extends Mystatic //定義一個(gè)子類 { static function test() //定義子類的靜態(tài)方法 { self::$a++; //訪問并操作父類的靜態(tài)變量 return self::$a; } } $obj1=new Mystatic; //新建父類對(duì)象 echo '此時(shí)$a的值為: '.$obj1->test().PHP_EOL;?????//通過對(duì)象調(diào)用靜態(tài)方法test,靜態(tài)屬性$a的值+1 $obj2=new?Mystatic;??????????????????????????????//新建另一個(gè)父類對(duì)象 echo?'此時(shí)$a的值為:?'.$obj2->test().PHP_EOL;?????//新父類對(duì)象調(diào)用靜態(tài)方法test,靜態(tài)屬性$a的值+1+1 $obj3=new?Mystatic2;?????????????????????????????//新建子類對(duì)象 echo?'此時(shí)$a的值為:?'.$obj3->test().PHP_EOL;?????//子類對(duì)象調(diào)用同名靜態(tài)方法test,?靜態(tài)屬性$a的值+1+1+1 echo?Mystatic::$a.PHP_EOL;????//通過父類::直接訪問靜態(tài)成員$a變量 echo?$obj1::$a.PHP_EOL;???//通過對(duì)象名::可以直接訪問靜態(tài)成員$a變量 ?>
Result:
此時(shí)$a的值為:?1 此時(shí)$a的值為:?2 此時(shí)$a的值為:?3 3 3
2. Static method
Subclasses can override the static methods of the parent class.
<?php class Mystatic1 { public static function getclassName() { return __CLASS__; } public static function whoclassName() { echo self::getclassName().PHP_EOL; } } class Mystatic2 extends Mystatic1{ public static function getclassName() { return __CLASS__; } } echo Mystatic1::getclassName().PHP_EOL; echo Mystatic2::getclassName().PHP_EOL; ?>
The class name of the current class can be obtained through
__CLASS__. We call the getClassName
method of the two classes respectively: Result:
Mystatic1 Mystatic2
indicates that the subclass overrides the static method of the same name of the parent class. Similarly, we can also call the
whoclassName method in the parent class on the subclass: <pre class="brush:php;toolbar:false"><?php
class Mystatic1 {
public static function getclassName() {
return __CLASS__;
}
public static function whoclassName() {
echo self::getclassName().PHP_EOL;
}
}
class Mystatic2 extends Mystatic1{
public static function getclassName() {
return __CLASS__;
}
}
echo Mystatic1::whoclassName();
echo Mystatic2::whoclassName();
?></pre>
Result:
Mystatic1 Mystatic1
Why is the second printed result the parent class name
Mystatic1 instead of the subclass name Mystatic2
? This is because the $this
pointer always points to the reference object that holds it, while self
points to the class that holds it when it is defined instead of
Class when calling, in order to solve this problem, starting from PHP 5.3, a new feature called
Delayed static binding has been added.
延遲靜態(tài)綁定
延遲靜態(tài)綁定(Late Static Bindings)針對(duì)的是靜態(tài)方法的調(diào)用,使用該特性時(shí)不再通過 <span style="background-color:#fe2c24;">self::</span>
引用靜態(tài)方法,而是通過 static::
,如果是在定義它的類中調(diào)用,則指向當(dāng)前類
,此時(shí)和 self
功能一樣,如果是在子類或者其他類中調(diào)用,則指向調(diào)用該方法所在的類
。
<?php class Mystatic1 { public static function getclassName() { return __CLASS__; } public static function whoclassName() { echo static::getclassName().PHP_EOL; } } class Mystatic2 extends Mystatic1{ //self改為static public static function getclassName() { return __CLASS__; } } echo Mystatic1::whoclassName(); echo Mystatic2::whoclassName(); ?>
結(jié)果:
Mystatic1 Mystatic2
表明后期靜態(tài)綁定生效,即 static
指向的是調(diào)用它的方法所在的類,而不是定義時(shí),所以稱之為延遲靜態(tài)綁定。
此外,還可以通過 static::class
來指向當(dāng)前調(diào)用類的類名,例如我們可以通過它來替代 __CLASS__
,這樣上述子類就沒有必要重寫 getClassName
方法了:
<?php class Mystatic1 { public static function getclassName() { return static::class; } public static function whoclassName() { echo static::getclassName().PHP_EOL; } } class Mystatic2 extends Mystatic1{} echo Mystatic1::getclassName().PHP_EOL; echo Mystatic2::getclassName().PHP_EOL; echo Mystatic1::whoclassName(); echo Mystatic2::whoclassName(); ?>
結(jié)果:
Mystatic1 Mystatic2 Mystatic1 Mystatic2
同理,self::class
則始終指向的是定義它的類。
靜態(tài)與非靜態(tài)的區(qū)別
靜態(tài)屬性和方法可以直接通過類引用,所以又被稱作類屬性和類方法。非靜態(tài)屬性和非靜態(tài)方法需要實(shí)例化后通過對(duì)象引用,因此被稱作對(duì)象屬性和對(duì)象方法。
靜態(tài)屬性保存在類空間,非靜態(tài)屬性保存在對(duì)象空間。非靜態(tài)方法可以訪問類中的任何成員(包括靜態(tài)),靜態(tài)方法只能訪問類中的靜態(tài)成員。
靜態(tài)方法可以直接調(diào)用,類名調(diào)用和對(duì)象調(diào)用(
類名或self::
調(diào)用),但是非靜態(tài)方法只能通過對(duì)象調(diào)用(對(duì)象名或$this->
調(diào)用)。一個(gè)類的所有實(shí)例對(duì)象,共用類中的靜態(tài)屬性。如果修改了這個(gè)類靜態(tài)屬性,那么這個(gè)類的所有對(duì)象都能訪問到這個(gè)新值。
靜態(tài)方法和屬性的生命周期跟相應(yīng)的類一樣長(zhǎng),靜態(tài)方法和靜態(tài)屬性會(huì)隨著類的定義而被分配和裝載入內(nèi)存中。一直到線程結(jié)束,靜態(tài)屬性和方法才會(huì)被銷毀。 非靜態(tài)方法和屬性的生命周期和類的實(shí)例化對(duì)象一樣長(zhǎng),只有當(dāng)類實(shí)例化了一個(gè)對(duì)象,非靜態(tài)方法和屬性才會(huì)被創(chuàng)建,而當(dāng)這個(gè)對(duì)象被銷毀時(shí),非靜態(tài)方法也馬上被銷毀。靜態(tài)方法和靜態(tài)變量創(chuàng)建后始終使用同一塊內(nèi)存,而使用實(shí)例的方式會(huì)創(chuàng)建多個(gè)內(nèi)存。但靜態(tài)方法效率上要比實(shí)例化高,靜態(tài)方法的缺點(diǎn)是不自動(dòng)進(jìn)行銷毀,而實(shí)例化的則可以做銷毀。
應(yīng)用場(chǎng)景:
靜態(tài)方法最適合工具類中方法的定義;比如文件操作,日期處理方法等.
靜態(tài)變量適合全局變量的定義.
推薦學(xué)習(xí):《PHP視頻教程》
The above is the detailed content of What is the static method of php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The "undefinedindex" error occurs because a key that does not exist in the array is accessed. Solutions include: 1. Use isset() to check whether the key exists, which is suitable for processing user input; 2. Use array_key_exists() to determine whether the key is set, and it can be recognized even if the value is null; 3. Use the empty merge operator?? to set the default value to avoid directly accessing undefined keys; in addition, you need to pay attention to common problems such as the spelling of form field names, the database result is empty, the array unpacking is not verified, the child keys are not checked in foreach, and the session_start() is not called.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.
