PHP Magic Method __set __get method

Source: Internet
Author: User
Look first. Official DocumentsThe explanation
__set () is the run when writing data to inaccessible properties.
__get () is utilized for reading data from inaccessible properties.
How do you translate it in Chinese? Inaccessible:n. Hard to reach, difficult to access, incomprehensible.
There is the truth in code:

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

?>

Results:
If there is no __get method, execution of Var_dump ($s->a) var_dump ($s->b) can have fatal errors
If there is no __get method, the execution of Var_dump ($s->e) has a notice, prompting that no attribute is defined $e
Summarize:
1. When reading data from an inaccessible property, the __get () method is called
2. When assigning values to an inaccessible property, the __set () method is called
3. Difficult to access includes: (1) Private attributes, (2) Properties without initialization
4. __isset () __unset () is similar

The above describes the PHP magic method __set __get method, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.