search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP magic methods __iset, __unset (code example)

Objectives of this article:

1. Understand the definition of magic methods in PHP

2. Understand the usage scenarios of __isset() magic method

3. Master the usage of __isset() magic method

4. Understand the usage scenarios of __unset() magic method

5. Master the usage of __unset() magic method

(1) Understand the definition of magic methods in PHP

PHP Reserve all class methods starting with __ (two underscores) as magic methods. Therefore, when defining class methods, except for the above magic methods, it is recommended not to prefix them with __.

There is another name for these two magic methods, they can also be called Magic methods of attribute overloading

So so far we have learned 4 magic methods of attribute overloading, as well as the other two __get and __set

in the previous article

(2)Understand the usage scenarios of __isset() magic method

When we want to not report an error when in isset (non-existent attribute) or empty (non-existent attribute), we can define the __isset magic method in the class, and it will be automatically executed at this time

(3), Master the usage of __isset() magic method

# #Summary:

1. In PHP, __isset is defined in the class in the following format: public function __isset (parameter 1). Note here that there must be two __, it must be __isset, and it must be With 1 parameter, one more or less will not work

2. When isset does not exist for an attribute, the system will automatically trigger the defined __isset method of the class where the object is located

3. When empty() does not exist, the system will automatically trigger the defined __isset method of the class where the object is located.

Each summary is derived through practice. Now we use practice to demonstrate the summary. , this can promote understanding and make each summary clearer and more intuitive

##Case 1,

Practical goal:

1. In PHP, __isset is defined in the class in the following format: public function __isset (parameter 1). Note here that there must be two __, which must be __isset, and must be brought 1 parameter, one more or less will not work

The specific code is as follows:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法 
    public  function __isset($name){
        echo "自动执行了Animal类中的__isset方法<br/>";
    }
}
$ani = new Animal();
?>

The running result is as follows:

Blank , indicating that no error was reported


Now let’s try it without adding parameters

The specific code is as follows:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法 
    public  function __isset(){
        echo "自动执行了Animal类中的__isset方法<br/>";
    }
}
$ani = new Animal();
?>

The running results are as follows:

Fatal error: Method Animal::__isset() must take exactly 1 argument in D:\E-class\class-code\classing\index.php on line 11

It can be seen that the __isset method has and can only have one parameter

Case 2,

Practice goals:

#1. When isset does not exist, the system will automatically trigger the object The defined __isset method of the class ##The specific code is as follows:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法 
    public  function __isset($name){
        echo "自动执行了Animal类中的__isset方法<br/>";
    }
}
$ani = new Animal();
isset($ani->name);
?>

The running results are as follows:

Automatically execute the __isset method in the Animal class

我们发现其实我们没有手动的去调用__isset方法,也就是说没有写成$ani->__isset(),但是这个方法依然执行了,因为什么呢?因为我们写了isset($ani->name);而这个name属性没有在类中定义,然后这个类中又定义了这个魔术方法,所以它就像魔术一样,突然就被自动执行了

这里一定要注意,是2个下划线,不是一个,否则就不是魔术方法了,下面还是再来做下测试

具体代码如下:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法 试着少写一个_
    public  function _isset($name){
        echo "自动执行了Animal类中的__isset方法<br/>";
    }
}
$ani = new Animal();
isset($ani->name);
?>

运行结果如下:

空白

说明刚刚那个__isset方法没有被自动执行了,所以一定要注意是2个下划线,就好像构造函数和析构函数一样,都是两个下划线

案例三、

实践目标:

1、当empty()不存在的属性时,系统会自动触发对象所在类的定义好的__isset方法

具体代码如下:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public  function __isset($name){
        echo "自动执行了Animal类中的__isset方法<br/>";
    }
}
$ani = new Animal();
empty($ani->name);
?>

运行结果如下:

自动执行了Animal类中的__isset方法

由此可见,会自动触发类中定义好的__iset魔术方法的场景,除了在isset不存在的属性时,还在empty不存在的属性时

(四)、了解__unset()魔术方法的使用场景

当希望在unset()不存在的属性时可以自定义自己的逻辑,我们可以在类中定义__unset方法,此刻它会被自动执行,我们可以在里面写自定义逻辑

(五)、掌握__unset()魔术方法的用法

总结:

1、PHP中__unset在类中定义格式如下 public function __unset(参数1),这里注意必须是2个__,必须是__unset,而且必须是要带1个参数,多一个少一个都不行

2、当unset不存在的属性时,系统会自动触发对象所在类的定义好的__unset方法

每个总结都是通过实践得出来的,现在我们用实践来演示总结,这样可以促进理解,让每个总结理解起来更加清晰,直观

案例一、

实践目标:

1、PHP中__unset在类中定义格式如下 public function __unset(参数1),这里注意必须是2个__,必须是__unset,而且必须是要带1个参数,多一个少一个都不行

具体代码如下:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public  function __unset($name){
        echo "自动执行了Animal类中的__unset方法<br/>";
    }
}
$ani = new Animal();
?>

运行结果如下:

空白

说明没有报错,现在我们来试着不写参数看下

具体代码如下:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public  function __unset(){
        echo "自动执行了Animal类中的__unset方法<br/>";
    }
}
$ani = new Animal();
?>

运行结果为:

Fatal error: Method Animal::__unset() must take exactly 1 argument in D:\E-class\class-code\classing\index.php on line 11

由此可见,__unset魔术方法,参数有且只能有一个

案例二、

实践目标:

1、当unset不存在的属性时,系统会自动触发对象所在类的定义好的__unset方法

具体代码如下:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public  function __unset($name){
        echo "自动执行了Animal类中的__unset方法<br/>";
    }
}
$ani = new Animal();
unset($ani->name);
?>

运行结果如下:

自动执行了Animal类中的__unset方法

我们发现其实我们没有手动的去调用__unset方法,也就是说没有写成$ani->__unset(),但是这个方法依然执行了,因为什么呢?因为我们写了unset($ani->name);而这个name属性没有在类中定义,然后这个类中又定义了这个魔术方法,所以它就像魔术一样,突然就被自动执行了

这里一定要注意,是2个下划线,不是一个,否则就不是魔术方法了,下面还是再来做下测试

具体代码如下:

<?php
class Animal{
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法 试着少写一个_
    public  function _unset($name){
        echo "自动执行了Animal类中的__unset方法<br/>";
    }
}
$ani = new Animal();
unset($ani->name);
?>

运行结果如下:

空白

由此可见,__unset魔术方法没有被自动执行了,所以一定要记得__unset魔术方法也是2个下划线

 (六)、总结

1、本文主要讲了__isset,__unset的使用场景,定义以及具体的实现方法

希望本文能给大家带来一定的帮助,谢谢!!!

The above is the detailed content of Detailed explanation of PHP magic methods __iset, __unset (code example). For more information, please follow other related articles on the PHP Chinese website!

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
How to implement hot update of function in PHP?How to implement hot update of function in PHP?May 15, 2025 pm 08:33 PM

There are three ways to implement hot updates for functions in PHP: 1. Rewrite the function and use runkit to dynamically rewrite the function; 2. Use OPcache to realize hot updates by restarting OPcache; 3. Use external tools such as deployer or ansible to automatically deploy and update code.

How to replace elements while iterating through PHP arrays?How to replace elements while iterating through PHP arrays?May 15, 2025 pm 08:30 PM

In PHP, you can use the following methods to traverse and replace array elements: 1. Use a foreach loop and reference (&$value) to modify the elements, but be aware that references may cause side effects. 2. Use a for loop to directly access indexes and values ​​to avoid reference problems. 3. Use the array_map function to make concise modifications, but the key name will be reset. 4. Use the array_walk function to modify the value and retain the key name. Performance, side effects and key name retention requirements should be taken into account when selecting a method.

How to verify ISBN strings in PHP?How to verify ISBN strings in PHP?May 15, 2025 pm 08:27 PM

Verifying ISBN strings in PHP can be implemented through a function that can handle two formats: ISBN-10 and ISBN-13. 1. Remove all non-numeric characters. 2. For ISBN-10, weighted sum calculation is used, and it is valid if the result can be divided by 11. 3. For ISBN-13, different weighting sum calculations are used, and it is valid if the result can be divided by 10. This function returns a Boolean value indicating whether the ISBN is valid.

How to implement automatic loading of classes in PHP?How to implement automatic loading of classes in PHP?May 15, 2025 pm 08:24 PM

In PHP, automatically loading classes are implemented through the __autoload or spl_autoload_register function. 1. The __autoload function has been abandoned, 2. The spl_autoload_register function is more flexible, supports multiple automatic loading functions, and can handle namespace and performance optimization.

How to modify array elements in PHP?How to modify array elements in PHP?May 15, 2025 pm 08:21 PM

Methods to modify array elements in PHP include direct assignment and batch modification using functions. 1. For indexed arrays, such as $colors=['red','green','blue'], the second element can be modified by $colors[1]='yellow'. 2. For associative arrays, such as $person=['name'=>'John','age'=>30], the value of age can be modified by $person['age']=31. 3. Use array_map or array_walk functions to modify array elements in batches, such as $numbers=array_map(fun

How to implement hook function in PHP?How to implement hook function in PHP?May 15, 2025 pm 08:18 PM

Implementing hook functions in PHP can be implemented through observer mode or event-driven programming. The specific steps are as follows: 1. Create a HookManager class to register and trigger hooks. 2. Use the registerHook method to register the hook and trigger the hook by the triggerHook method when needed. Hook functions can improve the scalability and flexibility of the code, but pay attention to performance overhead and debugging complexity.

PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

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

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),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment