PHP魔术方法的使用示例 |
本文标签:PHP,魔术方法 ① __get/__set:将对象的属性进行接管 当访问一个不存在的对象属性时: index.php 复制代码 代码如下: <?php define(BASEDIR,__DIR__); //定义根目录常量 include BASEDIR./Common/Loader.php; spl_autoload_register(\\Common\\Loader::autoload); $obj = new \Common\Object(); //在php中访问一个不存在的对象属性时 会抛出一个错误:Notice: Undefined property: Common\Object::$title in D:\practise\php\design\psr0\index.php on line 9 当在Common/Object.php 中添加 __set 和 __get 方法后 Object.php 复制代码 代码如下: <?php namespace Common; class Object{ 再执行 index.php,不会再报错 。 再次修改 Common/Object.php 复制代码 代码如下: <?php namespace Common; class Object{ index.php 复制代码 代码如下: <?php define(BASEDIR,__DIR__); //定义根目录常量 include BASEDIR./Common/Loader.php; spl_autoload_register(\\Common\\Loader::autoload); $obj = new \Common\Object(); $obj->title = hello; 执行 index.php,页面输出: 复制代码 代码如下: string Common\Object::__set (length=20) string Common\Object::__get (length=20) hello ② __call/__callStatic:控制 PHP 对象方法的调用(__callStatic 用来控制类的静态方法) 当执行一个不存在的php方法时 index.php: 复制代码 代码如下: <?php define(BASEDIR,__DIR__); //定义根目录常量 include BASEDIR./Common/Loader.php; spl_autoload_register(\\Common\\Loader::autoload); $obj = new \Common\Object(); //当执行一个不存在的php方法时 执行 index.php 会报一个致命错误:Fatal error: Call to undefined method Common\Object::test() in D:\practise\php\design\psr0\index.php on line 9 如果在 Common/Object 中定义一个__call 方法,则会在方法不存在时自动回调: 复制代码 代码如下: <?php namespace Common; class Object{ index.php 复制代码 代码如下: <?php define(BASEDIR,__DIR__); //定义根目录常量 include BASEDIR./Common/Loader.php; spl_autoload_register(\\Common\\Loader::autoload); $obj = new \Common\Object(); //当执行一个不存在的php方法时 页面输出: 复制代码 代码如下: string test (length=4) array 0 => string hello (length=5) 1 => int 123 magic function 当调用一个不存在的静态方法时 Common/Object.php 复制代码 代码如下: <?php namespace Common; class Object{ 注意:__callStatic 方法也要声明成静态方法 index.php 复制代码 代码如下: <?php define(BASEDIR,__DIR__); //定义根目录常量 include BASEDIR./Common/Loader.php; spl_autoload_register(\\Common\\Loader::autoload); //执行一个不存在的静态方法 执行 index.php ,页面输出: 复制代码 代码如下: string test (length=4) array 0 => string hello (length=5) 1 => int 1234 magic function ③ __toString:将一个 PHP 对象转换成一个字符串 index.php 复制代码 代码如下: <?php define(BASEDIR,__DIR__); //定义根目录常量 include BASEDIR./Common/Loader.php; spl_autoload_register(\\Common\\Loader::autoload); $obj = new \Common\Object(); echo $obj; 此时会报错: Catchable fatal error: Object of class Common\Object could not be converted to string in D:\practise\php\design\psr0\index.php on line 8 在 Object.php 中添加 __toString 方法 复制代码 代码如下: <?php namespace Common; class Object{ ④ __invoke:将一个 PHP 对象当成一个函数来执行时,会回调此魔术方法 index.php 复制代码 代码如下: <?php define(BASEDIR,__DIR__); //定义根目录常量 include BASEDIR./Common/Loader.php; spl_autoload_register(\\Common\\Loader::autoload); $obj = new \Common\Object(); echo $obj("test"); Object.php 复制代码 代码如下: <?php namespace Common; class Object{ 页面输出: 复制代码 代码如下: string test (length=4) invoke |