zoukankan      html  css  js  c++  java
  • php类相关知识---__unset和__isset

    __unset 删除非公有属性,在外部调用unset时发生,  __isset用来检测对象属性是否设置值

    <?php
    class coach
    {
        protected $chairfit = "徐晓冬";
        protected $lover = "丁大锅";
        public function __construct()
        {
            echo "欢迎来到~必图拳馆训练~";
        }
        public function __get($chairfit)
        {
            return $this->$chairfit;
        }
        public function __set($name,$value)
        {
            $this->$name=$value;
        }
    }
    class cj extends coach
    {
       public $expertin = ['散打','泰拳','巴西柔术'];
    }
    $cj = new cj();
    var_dump($cj);
    $cj->lover='陈培昌';
    var_dump(isset($cj->lover)) ;
    ?>

    以为这样就能检测非公有属性是否设置?deeply sorry about that!

    输出结果:

    欢迎来到~必图拳馆训练~
    bool(false)

    正确姿势
    
    <?php
    class coach
    {
        protected $chairfit = "徐晓冬";
        protected $lover = "丁大锅";
        public function __construct()
        {
            echo "欢迎来到~必图拳馆训练~"."
    ";
        }
        public function __get($chairfit)
        {
            return $this->$chairfit;
        }
        public function __set($name,$value)
        {
            $this->$name=$value;
        }
       #加上这段
    public function __isset($name) { return isset($name); } } class cj extends coach { public $expertin = ['散打','泰拳','巴西柔术']; } $cj = new cj(); //var_dump($cj); $cj->lover='陈培昌'; var_dump(isset($cj->lover)) ; ?>

    输出结果:

    欢迎来到~必图拳馆训练~
    bool(true)

    <?php
    class coach
    {
        protected $chairfit = "徐晓冬";
        private $lover;
        public function __construct()
        {
            echo "欢迎来到~必图拳馆训练~"."
    ";
        }
        public function __get($chairfit)
        {
            return $this->$chairfit;
        }
        public function __set($name,$value)
        {
            $this->$name=$value;
        }
        public function __isset($name)
        {
            return isset($name);
        }
        public function __unset($name)
        {
            unset($this->$name);
        }
    }
    class cj extends coach
    {
       public $expertin = ['散打','泰拳','巴西柔术'];
    }
    $cj = new coach();
    //var_dump($cj);
    $cj->lover='陈培昌';
    var_dump($cj);
    unset($cj->lover);
    var_dump($cj);
    
    ?>

    unset cj对象的lover属性之前,打印对象结果为:

    object(coach)#1 (2) {
    ["chairfit":protected]=>
    string(9) "徐晓冬"
    ["lover":"coach":private]=>
    string(9) "陈培昌"
    }

    删除之后打印对象结果

    object(coach)#1 (1) {
    ["chairfit":protected]=>
    string(9) "徐晓冬"
    }

  • 相关阅读:
    第四章 源代码的下载和编译 心得笔记
    第三章 Git使用入门 心得笔记
    第二章 搭建Android开发环境 心得笔记
    第一章 Android系统移植与驱动开发概述 心得笔记
    第十章
    第九章
    第八章
    第七章
    第六章
    第五章的体会
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/10959884.html
Copyright © 2011-2022 走看看