Blogger Information
Blog 40
fans 0
comment 0
visits 37599
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP学习总结(10)魔术方法的实例---2019年10月8号20:00分
虎子爸爸
Original
632 people have browsed it

总结:这个魔术方法类似于构造方法,只是用途不一样!

实例代码:

实例

<?php
namespace User;
class Info{
    public $name;
    public static function del(){

    }
    public function __set($name,$value){
        
        echo $name."不存在,触发了__set()方法";
    }
    public function __get($name){
        echo $name."不存在,触发了__get()方法";
    }
    public function __isset($name){
        echo $name."不存在,触发了__isset()方法";
    }
    public function __unset($name){
        echo $name."不存在,触发了__unset()方法";
    }
    public function __call($name,$arguments){
        echo $name."方法不存在,触发了__call()方法";
    }
    public static function __callStatic($name,$arguments){
        echo $name."静态方法不存在,触发了__callStatic()方法";
    }

}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <?php
    $info = new Info();
    ?>
    <p>
    echo $info->phone;<br>
    <?php
    echo $info->phone;
    echo "<br>";
    ?>

    </p>
    <p>
    $info->phone="123456";<br>
    <?php
    $info->phone="123456";
    echo "<br>";
    ?>

    </p>
    <p>
    var_dump(isset($info->phone));<br>
    因为phone不存在,所以isset($info->phone)先触发__isset()魔术方法<br>
    然后再执行isset函数,因为phone没有赋值所以得到一个布尔值false;<br>
        <?php
        var_dump(isset($info->phone));
        ?>
    </p>
    <p>
        unset($info->phone);这里想销毁phone属性,但是不存在,就触发了__unset($name)方法<br>
        <?php
        unset($info->phone);
        ?>
    </p>
    <p>
    $info->add();<br>
    当我们调用实例化对象里面不存在的方法时,就会触发__call()方法<br>
        <?php
        $info->add();

        ?>
    </p>
    <p>
        Info::edit();<br>
        当我们调用类里面一个不存在的静态方法时,触发__callStatic()方法<br>
        <?php
        Info::edit();

        ?>
    </p>

</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:其实没有写完, 下次写完再提交吧
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post