博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP 设计模式 笔记与总结(5)PHP 魔术方法的使用
阅读量:6969 次
发布时间:2019-06-27

本文共 1562 字,大约阅读时间需要 5 分钟。

PHP 魔术方法的使用

① __get/__set:将对象的属性进行接管

当访问一个不存在的对象属性时:

index.php

title;

会抛出一个错误:Notice: Undefined property: Common\Object::$title in D:\practise\php\design\psr0\index.php on line 9

当在Common/Object.php 中添加 __set 和 __get 方法后

Object.php

再执行 index.php,不会再报错。

再次修改 Common/Object.php

array[$key] = $value; } function __get($key){ var_dump(__METHOD__); return $this->array[$key]; }}

index.php

title = 'hello';echo $obj->title;

执行 index.php,页面输出:

string 'Common\Object::__set' (length=20)string 'Common\Object::__get' (length=20)hello

 

 

② __call/__callStatic:控制 PHP 对象方法的调用(__callStatic 用来控制类的静态方法)

当执行一个不存在的php方法时

index.php:

test('hello',123);

执行 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 方法,则会在方法不存在时自动回调:

index.php

test('hello',123);

页面输出:

string 'test' (length=4)array  0 => string 'hello' (length=5)  1 => int 123magic function

 

当调用一个不存在的静态方法时

Common/Object.php

注意:__callStatic 方法也要声明成静态方法

index.php

执行 index.php ,页面输出:

string 'test' (length=4)array  0 => string 'hello' (length=5)  1 => int 1234magic function

 

 

③ __toString:将一个 PHP 对象转换成一个字符串

index.php

此时会报错: 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 方法

此时再执行 index.php,输出:

Common\Object

 

④ __invoke:将一个 PHP 对象当成一个函数来执行时,会回调此魔术方法

index.php

Object.php

页面输出:

string 'test' (length=4)invoke

 

转载地址:http://yuasl.baihongyu.com/

你可能感兴趣的文章
[PWA] Cache JSON Data in a React PWA with Workbox, and Display it while Offline
查看>>
C++之List的用法,reference,参考,手册,man,帮助,
查看>>
yijing64
查看>>
The Stanford NLP (Natural Language Processing) Group
查看>>
ECSHOP-搜索引擎收录利器快速提升收录
查看>>
html页面实现指定位置的跳转
查看>>
c++学习笔记5
查看>>
【转】依赖抽象,不要依赖具体
查看>>
Creating a Swap Partition
查看>>
点击表格获取表格行或列索引
查看>>
不区分大小写
查看>>
AngularJs的MVC模式
查看>>
Linux终端会话实时共享(kibitz)
查看>>
“一键制作启动u盘失败”的主要原因是什么?
查看>>
Asp.Net上传文件到Access数据中,并从数据库中读取文件并保存
查看>>
【转】libvirt kvm 虚拟机上网 – Bridge桥接
查看>>
c/c++ helloworld
查看>>
xopy写批处理的忌讳..
查看>>
为程序添加系统上下文菜单
查看>>
css色彩对应值
查看>>