PHP special methods __set(), __get()_PHP tutorial

WBOY
Release: 2016-07-12 09:04:23
Original
907 people have browsed it

PHP special methods __set(), __get()

 <?php
    header("Content-type: text/html; charset=utf-8"); 
    class person{
        //成员属性
        private $name;
        private $age = 20;
        //成员方法
        function username($name){
            return $this->name=$name;
        }
        //__set()方法用来设置私有属性
        function __set($property_name, $value) { 
        echo "在直接设置私有属性值的时候,自动调用了这个 __set() 方法为私有属性赋值<br />";
        $this->$property_name = $value; 
        }
 
        //__get()方法用来获取私有属性
        function __get($property_name) {  
        echo "在直接获取私有属性值的时候,自动调用了这个 __get() 方法<br />";
        }
    }
    $obj= new person();
    echo $obj->username("张三");
    echo "<hr/>";
    $obj->name = "李四";//在直接设置私有属性值的时候,自动调用了这个 __set() 方法为私有属性赋值
    echo "<hr/>";
    echo $obj->age;//在直接获取私有属性值的时候,自动调用了这个 __get() 方法,不设置get特殊方法就会报下面的错
    //echo $obj->age;//当成员属性或者方法前有private修饰,不能在类外访问。否则报错如下
    /*
     Fatal error: Cannot access private property person::$age in D:\wamp\www\ajax\index.php on line 23
    */
?>
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1073354.htmlTechArticlePHP special methods __set(), __get() ?php header(Content-type: text/html; charset =utf-8); class person{ //Member attribute private $name; private $age = 20; //Member method function usern...
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