PHP magic method __set __get method

WBOY
Release: 2016-07-29 09:02:13
Original
907 people have browsed it

First take a look at the explanation of the official document
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
How to translate it in Chinese? inaccessible: n. Difficult to reach; difficult to approach; incomprehensible.
There is code and there is truth:

<?php

error_reporting(E_ALL);

class stu{

private $a;

​​​​private$b= 0;

public $c;

0;

//Here private can be replaced by protected public

private

function

__get($name) {                                                                                                             //Here private can also be replaced by protected public

private function __set(

$name, $value

) {

                                                                                                  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?> There will be a fatal errorIf there is no __get method, there will be a notice when executing var_dump($s->e), prompting that the attribute $e is not definedSummary:

1. When reading data from an inaccessible attribute The __get() method is called

2. The __set() method is called when assigning a value to an inaccessible property3. Inaccessible properties include: (1) private properties, (2) uninitialized properties4. __isset () __unset() is also similar The above introduces the PHP magic method __set __get method, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template