执行 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 CommonObject(); echo $obj;
此时会报错: Catchable fatal error: Object of class CommonObject could not be converted to string in D:practisephpdesignpsr0index.php on line 8 在 Object.php 中添加 __toString 方法 复制代码 代码如下: <?php namespace Common; class Object{ function __toString() { return __CLASS__; } }
④ __invoke:将一个 PHP 对象当成一个函数来执行时,会回调此魔术方法 index.php 复制代码 代码如下: <?php define("BASEDIR",__DIR__); //定义根目录常量 include BASEDIR."/Common/Loader.php"; spl_autoload_register("\Common\Loader::autoload"); $obj = new CommonObject(); echo $obj("test");
Object.php 复制代码 代码如下: <?php namespace Common; class Object{ function __invoke($param) { var_dump($param); return "invoke"; } }