Home > php教程 > php手册 > PHP 魔术方法 __get __set (二),__get__set

PHP 魔术方法 __get __set (二),__get__set

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-13 09:20:22
Original
1177 people have browsed it

PHP 魔术方法 __get __set (二),__get__set

慢慢长寻夜,明月高空挂

__get()  - 读取不可访问属性的值时,__get() 会被调用

__set()  - 在给不可访问属性赋值时,__set() 会被调用

<?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;
 
Copy after login

结果如下:

<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
Copy after login

 

Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template