当前位置:网站首页>The meaning of variables starting with underscores in PHP
The meaning of variables starting with underscores in PHP
2022-07-07 13:52:00 【Full stack programmer webmaster】
Named rules Add one as private Adding two is generally the system default , System predefined , The so-called : ===================== “ Magic methods ” And “ magic constant ” ===================== *PHP Constants that start and end with double underscores are “ magic constant ”:
__LINE__ The current line number in the file .
__FILE__ The full path and filename of the file .
__DIR__ Directory of files . If used in included files , Returns the directory where the included files are located . It is equivalent to dirname(__FILE__). Unless it's the root directory , Otherwise, the name in the directory does not include the trailing slash
notes : The above is from “PHP Chinese Manual -> Language reference -> Constant -> magic constant ”.
from php5 Later versions ,php Class can use magic methods .
php Specify two underscores (__) The first methods are reserved as magic methods , So it's better not to use function names __ start , Except for the purpose of overloading existing magic methods .
PHP There are many magic methods in :__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sleep, __wakeup, __toString, __set_state, __clone, __autoload
1、__get、__set
These two methods are designed for properties that are not declared in classes and their parent classes
__get( $property ) When calling an undefined property , This method will be triggered , The parameter passed is the name of the property being accessed
__set( property, value ) When assigning a value to an undefined property , This method will be triggered , The parameters passed are the name and value of the set property
There is no declaration here, including when using object calls , Access control is proteced,private Properties of ( That is, there is no access to the property ).
2、__isset、__unset
__isset( $property ) When called on an undefined property isset() Function
__unset( $property ) When called on an undefined property unset() Function
And __get Methods and __set In the same way , There is no declaration here, including when using object calls , Access control is proteced,private Properties of ( That is, there is no access to the property )
3、__call
__call( method, arg_array ) When you call an undefined method, you call this method
The undefined methods here include methods that do not have permission to access ; If the method does not exist, go to the parent class to find this method , If the parent class does not exist, call the __call() Fang ? Law , If it does not exist in this class __call() Method is to find the __call() Method
4、__autoload
__autoload function , It will automatically call when trying to use a class that has not been defined . By calling this function , The script engine is in PHP There was a last chance to load the required classes before the error failed .
If you want to define a global automatic loading class , You have to use spl_autoload_register() Method registers the processing class to PHP Standard library :
<?php
class Loader
{
static function autoload_class($class_name)
{
// Look for the right $class_name class , And introduce , If not, throw an exception
}
}
/**
* Set the automatic loading of objects
* spl_autoload_register — Register given function as __autoload() implementation
*/
spl_autoload_register(array('Loader', 'autoload_class'));
$a = new Test();//Test useless require Is instantiated , Implement automatic loading , Many frameworks use this method to automatically load classes
?>
Be careful : stay __autoload An exception thrown in a function cannot be catch Statement blocks capture and cause fatal errors , So capture should be done in the function itself .
5、__construct、__destruct
__construct Construction method , This method is called when an object is created , be relative to PHP4 The advantage of using this method is : You can give a constructor a unique name , Whatever the name of the class it's in . So when you change the name of a class , There is no need to change the name of the constructor
__destruct destructor ,PHP Before the object is destroyed ( That is, before clearing from memory ) Call this method . By default ,PHP Just release the memory occupied by the object properties and destroy the resources related to the object , Destructors allow you to clear memory by executing arbitrary code after using an object . When PHP When you decide that your script is no longer related to an object , The destructor will be called .
In the namespace of a function , This happens to the function return When .
For global variables , This happens at the end of the script .
If you want to explicitly destroy an object , You can assign any other value to the variable that points to the object . Usually the variable is assigned to NULL Or call unset.
6、__clone
PHP5 Object assignments in are reference assignments used , If you want to copy an object, you need to use clone Method , When this method is called, the object will automatically call __clone Magic methods , If you need to perform some initialization operation in object replication , Can be in __clone Method realization .
7、__toString
__toString Method is called automatically when converting an object to a string , For example, use echo When printing objects .
If the class does not implement this method , They can't get through echo Print object , Otherwise it will show :Catchable fatal error: Object of class test could not be converted to string in This method must return a string .
stay PHP 5.2.0 Before ,__toString Methods can only be used in combination echo() or print() when To take effect .PHP 5.2.0 after , Can take effect in any string environment ( For example, through printf(), Use %s Modifier ), but Cannot be used in non string environments ( If you use %d Modifier ). from PHP 5.2.0, If an undefined __toString Object of method Convert to string , Will report a E_RECOVERABLE_ERROR error .
8、__sleep、__wakeup
__sleep When serializing, use
__wakeup Called when deserializing
serialize() Check for magic names in the class __sleep Function of . If so , This function will run before any serialization . It clears the object and should return an array containing the names of all variables in the object that should be serialized .
Use __sleep The purpose of is to close any database connection that the object may have , Submit pending data or perform similar cleanup tasks . Besides , This function is also useful if you have very large objects and don't need to store them completely .
By contraries ,unserialize() Check for magic names __wakeup The existence of a function of . If there is , This function rebuilds any resources an object might have .
Use __wakeup The purpose of is to rebuild any database connections that may be lost in serialization and handle other reinitialization tasks .
9、__set_state
When calling var_export() when , This static Method will be called ( since PHP 5.1.0 Effective ).
The only argument to this method is an array , It includes pressing array(’property’ => value, …) Class properties of formatting .
10、__invoke
When trying to call an object as a function ,__invoke Method will be called automatically .
PHP5.3.0 The above version is valid
11、__callStatic
It works in a way similar to __call() Magic methods ,__callStatic() To handle static method calls ,
PHP5.3.0 The above version is valid PHP It really strengthens the right __callStatic() Method definition ; It has to be public , And must be declared static . Again ,__call() Magic methods have to be defined as public , All other magic methods must be like this .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/113267.html Link to the original text :https://javaforall.cn
边栏推荐
- Getting started with MySQL
- requires php ~7.1 -&gt; your PHP version (7.0.18) does not satisfy that requirement
- DID登陆-MetaMask
- 1、深拷贝 2、call apply bind 3、for of for in 区别
- [QNX hypervisor 2.2 user manual]6.3.4 virtual register (guest_shm.h)
- AI人才培育新思路,这场直播有你关心的
- Lavarel之环境配置 .env
- Milkdown control icon
- 供应链供需预估-[时间序列]
- 2022-7-6 sigurg is used to receive external data. I don't know why it can't be printed out
猜你喜欢
SSRF漏洞file伪协议之[网鼎杯 2018]Fakebook1
Social responsibility · value co creation, Zhongguancun network security and Information Industry Alliance dialogue, wechat entrepreneur Haitai Fangyuan, chairman Mr. Jiang Haizhou
实现IP地址归属地显示功能、号码归属地查询
Cinnamon taskbar speed
Supply chain supply and demand estimation - [time series]
Introduction to database system - Chapter 1 introduction [conceptual model, hierarchical model and three-level mode (external mode, mode, internal mode)]
2022-7-7 Leetcode 844. Compare strings with backspace
《厌女:日本的女性嫌恶》摘录
如何让join跑得更快?
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
随机推荐
mysql ”Invalid use of null value“ 解决方法
Mathématiques avancées - - chapitre 8 différenciation des fonctions multivariables 1
Ogre introduction
高等数学---第八章多元函数微分学1
DID登陆-MetaMask
move base参数解析及经验总结
Indoor ROS robot navigation commissioning record (experience in selecting expansion radius)
Battle Atlas: 12 scenarios detailing the requirements for container safety construction
JS function returns multiple values
Fast development board pinctrl and GPIO subsystem experiment for itop-imx6ull - modify the device tree file
Introduction and basic use of stored procedures
Learning breakout 2 - about effective learning methods
Redis can only cache? Too out!
1、深拷贝 2、call apply bind 3、for of for in 区别
Realize the IP address home display function and number home query
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
xshell连接服务器把密钥登陆改为密码登陆
2022-7-6 Leetcode27.移除元素——太久没有做题了,为双指针如此狼狈的一天
Deep understanding of array related problems in C language
SSRF漏洞file伪协议之[网鼎杯 2018]Fakebook1