Home>Article>Backend Development> How to use php __set magic method

How to use php __set magic method

青灯夜游
青灯夜游 Original
2021-06-18 18:06:44 1647browse

In PHP, the "__set()" method is automatically called when assigning values to undefined or invisible class attributes in the current environment; the syntax format is "public function __set($key, $value){ ...;}", which receives two parameters, one representing the attribute name and one representing the attribute value.

How to use php __set magic method

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

In object-oriented programming, PHP provides an A series of magic methods, these magic methods provide a lot of convenience for programming, and their role in PHP is very important. Magic methods in PHP usually start with __ (two underscores) and do not need to be explicitly called but are automatically called under certain conditions.

__set() method

The __set() method is automatically called when assigning a value to a class attribute that is undefined or invisible in the current environment. The syntax format for defining this method is as follows:

public function __set($key, $value){ ... ... ; }

Among them, the parameter $key is the name of the variable to be operated, and $value is the value of the variable $key.

[Example] The following uses a simple example to demonstrate the use of the __set() method.

'; } } $object = new Website(); $object -> name = 'php中文网'; $object -> url = '//m.sbmmt.com/'; $object -> title = 'PHP教程'; ?>

The running results are as follows:

为“url”赋值“//m.sbmmt.com/”失败! 为“title”赋值“PHP教程”失败!

Using the characteristics of the __set() method, we can use the __set() method to assign or modify the attributes modified with the private keyword in the class. . As shown below:

$key)){ $this -> $key = $value; }else{ echo '为“'.$key.'”赋值“'.$value.'”失败!
'; } } public function getUrl(){ echo $this -> url; } } $object = new Website(); $object -> name = 'php中文网'; $object -> url = '//m.sbmmt.com/'; $object -> title = 'PHP教程'; $object -> getUrl(); ?>

The running results are as follows:

为“title”赋值“PHP教程”失败! //m.sbmmt.com/

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to use php __set magic method. 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