search
HomeBackend DevelopmentPHP ProblemWhat is the difference between get and set in php

The difference between get and set in php: The "__get()" method is used to obtain the attribute value of a private member. The returned result is the obtained attribute value, while the "__set()" method is used to obtain the attribute value of a private member. When setting the value of a private member attribute, this method has no return value.

What is the difference between get and set in php

The operating environment of this tutorial: windows10 system, PHP7.1 version, DELL G3 computer

What is the difference between get and set in php

Generally speaking, always define the attributes of a class 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. It is similar to the operation of javabean in java, and the method used is similar, except that there is no need to perform set and get operations on each field like in javabean. Just add two magic methods. That is, the operations of setting and obtaining values ​​of private members.

In PHP5, we are provided with special methods for setting and obtaining values ​​for attributes, the two methods "__set()" and "__get()". These two methods do not exist by default, but We add them to the class manually. Like the constructor method (__construct()), it will only exist if it is 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:

//__set()方法用来设置私有属性
public function __set($name,$value){
$this->$name = $value;
}
//__get()方法用来获取私有属性
public function __get($name){
return $this->$name;
}
  • __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. , we don’t need to call this method manually, because we can also make this method a private method, which is automatically called by the object when the private attribute is directly obtained. Because the private property has been encapsulated, the value cannot be obtained directly. However, if you add this method to the class, you will automatically obtain the value directly when using a statement such as "echo$p1->name". Call the __get($name) method and pass the attribute name to the parameter $name. Through the internal execution of this method, the value of the private attribute we passed in is returned. 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 name of the attribute you want to set the value for. The first parameter is the value to be set for the attribute, and there is no return value. This method also does not need to be called manually. It can also be made private. 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 __set($property_name, $value) to the class ) This method will be automatically called when directly assigning a value to a private attribute. 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, the assignment is achieved. Purpose. 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:

class Person
{
    //下面是人的成员属性,都是封装的私有成员
    private $name; //人的名子
         private $sex; //人的性别
     private $age; //人的年龄
 
     //__get()方法用来获取私有属性
     public function __get($property_name)
    {
        echo "在直接获取私有属性值的时候,自动调用了这个__get()方法<br>";
        if (isset($this->$property_name)) {
            return ($this->$property_name);
       } else {
            return (NULL);
         }
     }
 
    //__set()方法用来设置私有属性
     public function __set($property_name, $value)
     {
         echo "在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值<br>";
         $this->$property_name = $value;
     }
 }
 
 $p1 = new Person();
 //直接为私有属性赋值的操作,会自动调用__set()方法进行赋值
 $p1->name = "张三";
 $p1->sex  = "男";
 $p1->age  = 20;
 //直接获取私有属性的值,会自动调用__get()方法,返回成员属性的值
 echo "姓名:" . $p1->name . "<br>";
 echo "性别:" . $p1->sex . "<br>";
 echo "年龄:" . $p1->age . "<br>";

Program execution result:

When directly setting the value of a private property, the __set() method is automatically called to assign a value to the private property

When directly setting the value of a private property When setting the value of a private attribute, the __set() method is automatically called to assign a value to the private attribute

When the value of a private attribute is set directly, the __set() method is automatically called to assign a value to the private attribute

When directly obtaining the private attribute value, this __get() method is automatically called

Name: Zhang San

When directly obtaining the private attribute value, the __get() method is automatically called This __get() method

Gender: Male

When directly obtaining the private attribute value, this __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 _ The _set() method helps us directly access the encapsulated private members.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the difference between get and set in php. 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development 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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!