search
Homephp教程php手册详解php的魔术方法__get()和__set()使用介绍

详解php的魔术方法__get()和__set()使用介绍

Jun 13, 2016 am 11:57 AM
getphprunsetwintroduceuseandofficialdocumentmethodofexplainDetailed explanationmagic

先看看php官方文档的解释:
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.

究竟用中文怎么翻译呢?
inaccessible :n. 难达到;难接近;无法理解。

有代码有真相:

复制代码 代码如下:


error_reporting(E_ALL);
class stu{
private $a;
private $b = 0;
public $c;
public $d = 0;
//这里的 private 可以用 protected public 替代
private function __get($name) {
return 123;
}

//这里的 private 也可以用 protected public 替代
private function __set($name, $value) {
echo "This is set function";
}
}
$s = new stu();
var_dump($s->a); //output: 123
var_dump($s->b); //output: 123
var_dump($s->c); //output: null
var_dump($s->d); //output: 0
var_dump($s->e); //output: 123
$s->a = 3; //output: This is set function
$s->c = 3; //no output
$s->f = 3; //output: This is set function
?>



结果分析:
如果没有__get方法,执行 var_dump($s->a) var_dump($s->b) 会有致命的错误
如果没有__get方法,执行 var_dump($s->e) 会有一个notice,提示没有定义属性 $e

总结:
1. 从一个难以访问的属性读取数据的时候 __get() 方法被调用
2. 向一个难以访问的属性赋值的时候 __set() 方法被调用
3. 难以访问包括:(1)私有属性,(2)没有初始化的属性
4. __isset() __unset() 也类似
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

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools