Home Backend Development PHP Tutorial Detailed explanation of PHP5 object-oriented - (10) __set() __get() __isset() __unset() four methods_PHP tutorial

Detailed explanation of PHP5 object-oriented - (10) __set() __get() __isset() __unset() four methods_PHP tutorial

Jul 13, 2016 pm 05:13 PM
get isset p php5 set unset one time introduce about object article method of Simple Detailed explanation For

This article briefly introduces the detailed explanation of PHP5 object-oriented - (10) __set() __get() __isset() __unset() four methods. Friends who need help can refer to it.

__set() __get() __isset() __unset() Application of four methods
Generally speaking, always define class attributes as private, which is more in line with realistic logic. However, reading and assigning operations to attributes are very frequent, so in PHP5, two functions "__get()" and "__set()" are predefined to obtain and assign attributes, and "__isset" to check attributes. ()" and the method to delete attributes "__unset()".

In the previous section, we set and obtained methods for each attribute. PHP5 provides us with special methods for setting and obtaining values ​​for attributes, "__set()" and "__get()" These two methods, these two methods do not exist by default, but are manually added to the class. Like the constructor method (__construct()), it will only exist if it is added to the class. You can add it in the following way. Of course, these two methods can also be added according to personal style:

The code is as follows Copy code
 代码如下 复制代码


//__get()方法用来获取私有属性  
function __get($property_name)  
{  
    if(isset($this->$property_name)) {  
        return($this->$property_name);  
    }else {  
        return(NULL);  
    }  
}   
 
//__set()方法用来设置私有属性  
function __set($property_name, $value)  
{  
    $this->$property_name = $value;  

//__get()方法用来获取私有属性
function __get($property_name)
{
    if(isset($this->$property_name)) {
        return($this->$property_name);
    }else {
        return(NULL);
    }
}

//__set()方法用来设置私有属性
function __set($property_name, $value)
{
 $this->$property_name = $value;
}__

//__get() method is used to obtain private attributes function __get($property_name) { If(isset($this->$property_name)) {           return($this->$property_name);                               }else {           return(NULL);                                      }   }  //__set() method is used to set private attributes function __set($property_name, $value) { $this->$property_name = $value; } //__get() method is used to obtain private attributes function __get($property_name) { If(isset($this->$property_name)) {           return($this->$property_name); }else {          return(NULL); } } //__set() method is used to set private properties function __set($property_name, $value) { $this->$property_name = $value; }__

get() method: This method is used to get the value of a private member attribute. It has one parameter. The parameter is passed in the name of the member attribute you want to get, and the obtained attribute value is returned. This method does not need to be called manually. It is automatically called when private properties are directly obtained. Because the private properties have been encapsulated, the value cannot be obtained directly (for example: "echo $p1->name" is wrong to obtain directly), but if you add this method to the class, use " When a statement like echo $p1->name" directly obtains the value, it will automatically call the __get($property_name) method and pass the property name to the parameter $property_name. Through the internal execution of this method, the private value we passed in will be returned. The value of the attribute.

__set() method: This method is used to set values ​​for private member attributes. It has two parameters. The first parameter is the name of the attribute you want to set the value for, and the second parameter is the value you want to set for the attribute. , no return value. This method also does not need to be called manually. It is automatically called when directly setting the private attribute value. The same private attribute has been encapsulated. If there is no __set() method, it is not allowed. For example: "$ this->name='zhangsan' , this will cause an error, but if you add the __set($property_name, $value) method to the class, it will be automatically called when you directly assign a value to the private property. Pass attributes such as name to $property_name, and pass the value "zhangsan" to be assigned to $value. Through the execution of this method, the purpose of assignment is achieved. In order not to pass in illegal values, you can also make a judgment in this method. .The code is as follows:

The code is as follows Copy code

class Person
{
//The following are the member attributes of people, all of which are encapsulated private members
Private $name; //Person’s name
Private $sex; //Person’s gender
Private $age; //Age of person

//__get() method is used to obtain private attributes
Function __get($property_name)

                                                                                                                with with echo "When directly obtaining the private attribute value, this __get() method is automatically called
"; If(isset($this->$property_name)) {
                 return($this->$property_name);                                                                                                                                 return(NULL);                                                                                                                             }  

//__set() method is used to set private attributes
Function __set($property_name, $value)

                    echo "When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute
"; 
            $this->$property_name = $value;                                           }  
}

$p1=new Person();

//If you directly assign a value to a private attribute, the __set() method will be automatically called for assignment
$p1->name="Zhang San";
$p1->sex="Male";
$p1->age=20;

//Get the value of the private attribute directly, and the __get() method will be automatically called to return the value of the member attribute
echo "Name:".$p1->name."
";
echo "Gender:".$p1->sex."
";
echo "Age:".$p1->age."
";

class Person
{
//The following are the member attributes of people, all of which are encapsulated private members
Private $name; //Person’s name
Private $sex; //Person’s gender

Private $age; //Age of person

//__get() method is used to obtain private attributes
Function __get($property_name)
{
               echo "When directly obtaining the private attribute value, this __get() method is automatically called
";
If(isset($this->$property_name)) {
              return($this->$property_name);
         }else {
             return(NULL);
}
}

//__set() method is used to set private attributes
Function __set($property_name, $value)
{
echo "When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute
";
$this->$property_name = $value;
}
}

$p1=new Person();

//When directly assigning values ​​to private attributes, the __set() method will be automatically called to assign values
$p1->name="Zhang San";
$p1->sex="Male";
$p1->age=20;

//Get the value of the private attribute directly, the __get() method will be automatically called to return the value of the member attribute
echo "Name:".$p1->name."
";
echo "Gender:".$p1->sex."
";
echo "Age:".$p1->age."
";

Program execution result:
When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute
When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute
When directly setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute
When directly obtaining the private attribute value, the __get() method is automatically called
Name: Zhang San
When directly obtaining the private attribute value, the __get() method is automatically called
Gender: Male
When directly obtaining the private attribute value, the __get() method is automatically called
Age: 20

If the above code does not add the __get() and __set() methods, the program will go wrong, because private members cannot be operated outside the class, and the above code automatically calls __get() and __set () method to help us directly access the encapsulated private members.

__isset() method: Before looking at this method, let’s take a look at the application of isset() function. isset() is a function used to determine whether a variable is set. Pass in a variable as a parameter. If the passed in variable exists, then Returns true, otherwise returns false.

So if you use the "isset()" function outside an object to determine whether the members inside the object are set, can you use it? There are two situations. If the members in the object are public, we can use this function to measure the member attributes. If they are private member attributes, this function will not work. The reason is that the private ones are encapsulated and are not exposed externally. Invisible. So we can't use the "isset()" function outside the object to determine whether the private member properties are set? Yes, you just need to add a "__isset()" method to the class. When the "isset()" function is used outside the class to determine whether the private members in the object are set, it will be automatically called inside the class. The "__isset()" method helps us complete such operations, and the "__isset()" method can also be made private. You can just add the following code to the class:

The code is as follows
 代码如下 复制代码

private function __isset($nm)  
{  
    echo "当在类外部使用isset()函数测定私有成员$nm时,自动调用";  
    return isset($this->$nm);  

private function __isset($nm)
{
 echo "当在类外部使用isset()函数测定私有成员$nm时,自动调用";
 return isset($this->$nm);
}

Copy code
private function __isset($nm) { echo "When the isset() function is used outside the class to determine the private member $nm, it is automatically called"; Return isset($this->$nm); } private function __isset($nm) { echo "Automatically called when the isset() function is used outside the class to determine the private member $nm"; return isset($this->$nm); }

__unset() method: Before looking at this method, let’s take a look at the "unset()" function first. The function of "unset()" is to delete the specified variable and return true. The parameters are deleted variable. So if you want to delete the member attributes inside the object outside an object, can you use the "unset()" function? There are two situations. If the member attributes inside an object are public, you can use this function to delete them outside the object. The public attributes of the object. If the member attributes of the object are private, I will not have the permission to delete them using this function. But similarly, if you add the "__unset()" method to an object, you can delete it from outside the object. Private member properties of the object. After adding the "__unset()" method to the object, when using the "unset()" function outside the object to delete the private member attributes inside the object, the "__unset()" function is automatically called to help us delete the private member attributes inside the object. Member attribute, this method can also be defined as private inside the class. Just add the following code to the object:

The code is as follows Copy code

private function __unset($nm)
{
echo "Automatically called when the unset() function is used outside the class to delete a private member";
Unset($this->$nm);
}

private function __unset($nm)
{
echo "Automatically called when the unset() function is used outside the class to delete a private member";
unset($this->$nm);
} Let’s take a look at a complete example:


class Person
{
//The following are the member attributes of people
Private $name; // Person’s name
Private $sex; // Person’s gender
Private $age; // The person’s age
//__get() method is used to obtain private attributes
Private function __get($property_name)

If (isset($this->$property_name)) {
                 return($this->$property_name);                                                                                                                   return(NULL);                                                                                                                            }  
// __set() method is used to set private attributes
Private function __set($property_name, $value)

            $this->$property_name = $value;                                           }  
// __isset() method
Private function __isset($nm)

              echo "The isset() function is automatically called when measuring private members";                                                return isset($this->$nm);                              }  
// __unset() method
Private function __unset($nm)

echo "Automatically called when the unset() function is used outside the class to delete a private member";
         unset($this->$nm);                       }  
}
$p1 = new Person();
$p1->name = "this is a person name";
// When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true
echo var_dump(isset($p1->name)) . "";
echo $p1->name . "";
// When using the unset() function to delete private members, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
// It has been deleted, so there will be no output for this line
echo $p1->name;

class Person
{
//The following are the member attributes of people
private $name; // person’s name
private $sex; // Person’s gender
private $age; // The person’s age
//__get() method is used to obtain private attributes

private function __get($property_name)

{
if (isset($this->$property_name)) {
Return($this->$property_name);
} else {
Return(NULL);
}
}
//The __set() method is used to set private attributes
private function __set($property_name, $value)
{
$this->$property_name = $value;
}
// __isset() method
private function __isset($nm)
{
echo "The isset() function is automatically called when measuring private members";
Return isset($this->$nm);
}
// __unset() method
private function __unset($nm)
{
echo "Automatically called when the unset() function is used outside the class to delete a private member";
unset($this->$nm);
}
}
$p1 = new Person();
$p1->name = "this is a person name";
// When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true
echo var_dump(isset($p1->name)) . "";
echo $p1->name . "";
// When using the unset() function to delete private members, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
// has been deleted, so there will be no output for this line
echo $p1->name;The output result is:

When the isset() function determines a private member, it is automatically called
bool(true)
this is a person name

When the isset() function determines a private member, it is automatically called
bool(true)
this is a person name __set(), __get(), __isset(), __unset()

are automatically called when the unset() function is used outside the class to delete private members.

These four methods are added to the object and automatically called when needed to complete the operation of the private properties inside the object outside the object

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629197.htmlTechArticleThis article briefly introduces the detailed explanation of PHP5 object-oriented - (10) __set() __get() __isset() There are four methods of __unset(). Friends who need help can refer to them. __set() __get() __i...
Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The difference between Go language methods and functions and analysis of application scenarios The difference between Go language methods and functions and analysis of application scenarios Apr 04, 2024 am 09:24 AM

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

See all articles