首页 > 代码库 > php 中的魔术方法-----“事件方法”

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:

php 中的魔术方法-----“事件方法”