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';會報錯 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; //定義一個靜態(tài)變量 static function test() //定義靜態(tài)方法來操作并輸出靜態(tài)變量 { self::$a++; return self::$a; } } class Mystatic2 extends Mystatic //定義一個子類 { static function test() //定義子類的靜態(tài)方法 { self::$a++; //訪問并操作父類的靜態(tài)變量 return self::$a; } } $obj1=new Mystatic; //新建父類對象 echo '此時$a的值為: '.$obj1->test().PHP_EOL;?????//通過對象調用靜態(tài)方法test,靜態(tài)屬性$a的值+1 $obj2=new?Mystatic;??????????????????????????????//新建另一個父類對象 echo?'此時$a的值為:?'.$obj2->test().PHP_EOL;?????//新父類對象調用靜態(tài)方法test,靜態(tài)屬性$a的值+1+1 $obj3=new?Mystatic2;?????????????????????????????//新建子類對象 echo?'此時$a的值為:?'.$obj3->test().PHP_EOL;?????//子類對象調用同名靜態(tài)方法test,?靜態(tài)屬性$a的值+1+1+1 echo?Mystatic::$a.PHP_EOL;????//通過父類::直接訪問靜態(tài)成員$a變量 echo?$obj1::$a.PHP_EOL;???//通過對象名::可以直接訪問靜態(tài)成員$a變量 ?>
Result:
此時$a的值為:?1 此時$a的值為:?2 此時$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)針對的是靜態(tài)方法的調用,使用該特性時不再通過 <span style="background-color:#fe2c24;">self::</span>
引用靜態(tài)方法,而是通過 static::
,如果是在定義它的類中調用,則指向當前類
,此時和 self
功能一樣,如果是在子類或者其他類中調用,則指向調用該方法所在的類
。
<?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(); ?>
結果:
Mystatic1 Mystatic2
表明后期靜態(tài)綁定生效,即 static
指向的是調用它的方法所在的類,而不是定義時,所以稱之為延遲靜態(tài)綁定。
此外,還可以通過 static::class
來指向當前調用類的類名,例如我們可以通過它來替代 __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(); ?>
結果:
Mystatic1 Mystatic2 Mystatic1 Mystatic2
同理,self::class
則始終指向的是定義它的類。
靜態(tài)與非靜態(tài)的區(qū)別
靜態(tài)屬性和方法可以直接通過類引用,所以又被稱作類屬性和類方法。非靜態(tài)屬性和非靜態(tài)方法需要實例化后通過對象引用,因此被稱作對象屬性和對象方法。
靜態(tài)屬性保存在類空間,非靜態(tài)屬性保存在對象空間。非靜態(tài)方法可以訪問類中的任何成員(包括靜態(tài)),靜態(tài)方法只能訪問類中的靜態(tài)成員。
靜態(tài)方法可以直接調用,類名調用和對象調用(
類名或self::
調用),但是非靜態(tài)方法只能通過對象調用(對象名或$this->
調用)。一個類的所有實例對象,共用類中的靜態(tài)屬性。如果修改了這個類靜態(tài)屬性,那么這個類的所有對象都能訪問到這個新值。
靜態(tài)方法和屬性的生命周期跟相應的類一樣長,靜態(tài)方法和靜態(tài)屬性會隨著類的定義而被分配和裝載入內存中。一直到線程結束,靜態(tài)屬性和方法才會被銷毀。 非靜態(tài)方法和屬性的生命周期和類的實例化對象一樣長,只有當類實例化了一個對象,非靜態(tài)方法和屬性才會被創(chuàng)建,而當這個對象被銷毀時,非靜態(tài)方法也馬上被銷毀。靜態(tài)方法和靜態(tài)變量創(chuàng)建后始終使用同一塊內存,而使用實例的方式會創(chuàng)建多個內存。但靜態(tài)方法效率上要比實例化高,靜態(tài)方法的缺點是不自動進行銷毀,而實例化的則可以做銷毀。
應用場景:
靜態(tài)方法最適合工具類中方法的定義;比如文件操作,日期處理方法等.
靜態(tài)變量適合全局變量的定義.
推薦學習:《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

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

InJava,thestatickeywordmeansamemberbelongstotheclassitself,nottoinstances.Staticvariablesaresharedacrossallinstancesandaccessedwithoutobjectcreation,usefulforglobaltrackingorconstants.Staticmethodsoperateattheclasslevel,cannotaccessnon-staticmembers,

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
