php 中的魔术方法-----“事件方法”
来源:http://lornajane.net/posts/2012/phps-magic-__invoke-method-and-the-callable-typehint
php 中的这个对象 ,有时间研究一下:
PHP中会有一些魔术方法:PHP 将所有以 __(两个下划线)开头的类方法保留为魔术方法。所以在定义类方法时,除了上述魔术方法,建议不要以 __ 为前缀。
魔术方法有:__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(),__wakeup(), __toString(), __invoke(), __set_state(), __clone() 和 __debugInfo() 等方法在 PHP 中被称为"魔术方法"(Magic methods)。在命名自己的类方法时不能使用这些方法名,除非是想使用其魔术功能。
Typehint
PHP has a variety of magic methods; methods named with two underscores at the start, which get called automatically when a particular event happens.(所以我标题中也叫事件方法,指特定的时间触发时,会自动调用,自动执行的方法。) In PHP 5.3, a new magic method was added: __invoke()
.
__invoke()
The __invoke()
method gets called when the object is called as a function. When you declare it, you say which arguments it should expect. Here's a trivially simple example:
class Butterfly { public function __invoke() { echo "flutter"; } }
We can instantiate a Butterfly object, and then just use it like a function:
$bob = new Butterfly(); $bob(); // flutter
If you try to do the same thing on an object without an __invoke()
method, you'll see this error:
PHP Fatal error: Function name must be a string in filename.php on line X
We can check if the object knows how to be called by using the is_callable()
function.
Callable Typehint
In PHP 5.4 (the newest version, and it has lots of shiny features), we have the Callable
typehint. This allows us to check whether a thing is callable, either because it's a closure, an invokable object, or some other valid callback. Another trivial example to continue the butterflies and kittens theme:
也就是说, php 中 callable类型一共有3种:
function sparkles(Callable $func) { $func(); return "fairy dust"; } class Butterfly { public function __invoke() { echo "flutter"; } } $bob = new Butterfly(); echo sparkles($bob); // flutterfairy dust
So there it is, one invokable object being passed into a function and successfully passing a Callable
typehint. I realise I also promised kittens, so here's a cute silver tabby I met the other day:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现