search
HomeBackend DevelopmentPHP TutorialPHP object-oriented guide (6) Usage of __set() __get() __isset() __unset()_PHP tutorial

10. Application of the four methods __set() __get() __isset() __unset()
Generally speaking, always define the attributes of a class as private, which is more in line with realistic logic. However, the reading
and assignment operations on attributes are very frequent, so in PHP5, two functions "__get()" and "__set()" are predefined to get
and assign their attributes. , as well as the "__isset()" method for checking attributes and the "__unset()" method for deleting attributes.
In the previous section, we have set and obtained methods for each attribute. In PHP5, we are provided with special methods for setting and obtaining values ​​for attributes
, "__set()" and " __get()". These two methods do not exist by default.
They are manually added to the class. Like the constructor method (__construct()), they will only exist if they are added to the class.
You can add these two methods in the following way, of course you can also add them according to your personal style:
Code snippet

Copy code The code is as follows:

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

__get() method: This method is used to obtain private members For attribute values, there is a 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, because we can also make the
method Private methods are automatically called by the object when private properties are directly obtained. Because the private attributes have been
encapsulated, the value cannot be obtained directly (for example: "echo $p1->name" is wrong to obtain directly),
but if you add With this method, when you use a statement such as "echo $p1->name" to directly obtain the value
, the __get($property_name) method will be automatically called and the attribute name will be passed to the parameter $property_name. Through this method The internal execution of , returns the value of the private property we passed in. If the member properties are not encapsulated as private, the object
itself will not automatically call this method.
__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. The second parameter is the attribute name you want to set the value to. Set value, no return value. This method also does not require us to
call it manually. It can also be made private. It is automatically called when directly setting the private attribute value. The same attribute
private has been encapsulated. If there is no __set () This method is not allowed, for example:
$this->name='zhangsan', this will cause an error, but if you add __set($property_name, $value)
This method will be automatically called when directly assigning a value to a private property. Pass the attribute such as name to
$property_name, and pass the value "zhangsan" to be assigned to $value. Through the execution of this method, To achieve the purpose of assignment
. If the member properties are not encapsulated as private, the object itself will not automatically call this method. In order not to pass in illegal
values, you can also make a judgment in this method. The code is as follows: Code snippet

Copy code The code is as follows:
class Person{
//The following are the member attributes of a person, which are all encapsulated private members
private $name; //The name of the person
private $sex; //The gender of the person
private $age; //The person's Age
//__get() method is used to obtain private properties
private function __get($property_name){
echo "When directly obtaining the private property value, this __get() method is automatically called< ;br>";
if(isset($this->$property_name)) {
return($this->$property_name);
}else {
return(NULL);
}
}
//__set() method is used to set private properties
private function __set($property_name, $value){
echo "When setting private property values ​​directly, This __set() method is automatically called to assign a value to the private property
";
$this->$property_name = $value;
}
}
$p1=new Person( );
//If you directly assign a value to a private attribute, the __set() method will be automatically called to assign the value. "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 results:
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. Assigning values ​​to private attributes
When directly setting the value of a private attribute, the __set() method is automatically called. Assigning a value to a private attribute
When directly obtaining the value of a private attribute, the __get() method is automatically called.
Name: Zhang San
When directly obtaining the private attribute value, this __get() method is automatically called
Gender: Male
When directly obtaining the private attribute value, this is automatically called __get() method
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. The above code helps us directly access the encapsulated private
members by automatically calling the __get() and __set() methods.
__isset() method: Before looking at this method, let’s take a look at the application of the “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 Returns true if it exists, otherwise returns false.
So if you use the "isset()" function outside an object to determine whether the members in 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 determine the member attributes. If they are private member attributes, this function will not work. The reason is that the private ones are encapsulated. , it is not visible from the outside
. Then we can't
use the "isset()" function outside the object to determine whether the private member attribute has been set? Yes, you just need to
add a "__isset()" method to the class. When using the "isset()" function outside the class to determine whether the private members in the object have been set
, the "__isset()" method in the class will be automatically called to help us complete such operations. The "__isset()" method can also be made private. You can just add the following code to the class:
Code snippet


Copy code The code is as follows:
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);
}


__unset() method: Before looking at this method, let’s take a look at the “unset()” function first, “unset()”
The function of this function is to delete the specified variable and return true. The parameter is the variable to be deleted. 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 a
object are public, you can use it. This function deletes the public attributes of the object outside 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 "__unset(( )" method, you can delete the private member attributes of the object outside 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 will be automatically called to help. We delete the private member attributes inside the object. This method can also be defined as private inside the class. Just add the following code to the object:
Code snippet



Copy code
The code is as follows: 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:
Code snippet



Copy code
The code is as follows:

class Person{
//The following are the member attributes of the person
private $name; //The person’s name
private $sex; //The person’s Gender
private $age; //Age of a person
//__get() method is used to obtain private properties
private function __get($property_name){
if(isset($this-> $property_name)){
return($this->$property_name);}else {
return(NULL);
}
}
}
//__set() Method used to set private properties
private function __set($property_name, $value){
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm){
echo "When the isset() function determines a private member, it is automatically called
";
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 name Private attribute
unset($p1->name);
//has been deleted, so there will be no output in this line
echo $p1->name;
?>

The output result is:
When the isset() function determines a private member, it automatically calls
bool(true)
this is a person name
When unset is used outside the class () function to delete private members. The four methods
__set(), __get(), __isset(), and __unset() are all added to the object and are
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/320645.htmlTechArticle10.__set() __get() __isset() __unset() Generally speaking, the application of the four methods It is to define the attributes of the class as private, which is more in line with realistic logic. However, reading and assigning values ​​to attributes...
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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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