Home  >  Article  >  Backend Development  >  PHP magic method: __get __set

PHP magic method: __get __set

WBOY
WBOYOriginal
2016-08-08 09:33:081164browse

From php5 and later versions, classes can use magic methods. PHP stipulates that methods starting with two underscores (__) are reserved as magic methods, so it is recommended that function names do not start with __ unless it is to overload existing magic methods.

The existing magic methods in PHP include __construct, __destruct, __call, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __set_state and __clone.

This section will talk about the usage of __get and __set:

__get() -When reading the value of an inaccessible attribute, __get() will be called

__set() -When assigning a value to an inaccessible property, __set() will be called

<?php

/**
 * 清晰的认识__get() __set()
 */
class Example {
    
    //公有的属性
    public $public = 'pub' ;
    //受保护的 - 子类中该属性可用
    protected $protected = 'pro';
    //私有的 - 只能此类使用此属性
    private $private = 'pri';
    
    //当访问对象中的属性不存在或者非公有属性的时候自动加载__get()方法
    public function __get($name){
        return '调用__get()方法:'.$name;
    }
    
    //当给对象的一个属性赋值的时候如果该属性不存在或者是非公有属性则自动加载__set()方法
    public function __set($name,$value){
        echo "\nname:".$name.',value:'.$value."\n";
    }
}

$example = new Example;
echo '<pre class="brush:php;toolbar:false">';
echo $example->public."\n";
echo $example->protected."\n";
echo $example->private."\n";
echo $example->other."\n";
echo '<hr>';
$example->public = 'lic';   //这个赋值成功所有没有显示
$example->protected = 'tec';
$example->private = 'vat';
$example->other = 'er';
echo '<br/>';
echo '打印 public 属性:'.$example->public;
 

The result is as follows:

<span>pub
调用__get()方法:</span><span>protected</span><span> 调用__get()方法:</span><span>private</span><span> 调用__get()方法:other

name:</span><span>protected</span>,value:<span>tec

name:</span><span>private</span>,value:<span>vat

name:other</span>,value:<span>er

打印 </span><span>public</span> 属性:lic

The above introduces the PHP magic method: __get __set, including the content of PHP magic method. I hope it will be helpful to friends who are interested in PHP tutorials.

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