Table of Contents
What is the difference between get and set in php
Home Backend Development PHP Problem What is the difference between get and set in php

What is the difference between get and set in php

Feb 10, 2022 pm 03:14 PM
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;
}
Copy after login
  • __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>";
Copy after login

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 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