PHP Magic constants: Difference between __FUNCTION__ and __METHOD__

今天我们来比较一下两个 PHP 魔术常量:__FUNCTION__ 和 __METHOD__。

首先看一下官方文档的定义,然后再用几个简单的例子来比较。

__FUNCTION__The function name, or {closure} for anonymous functions.
__METHOD__The class method name.

1. Class 里面的方法

<?php

namespace App;

class Test {
	public static function run() {
		echo __FUNCTION__ , "\n";
		echo __METHOD__ , "\n";
                echo __CLASS__ , '::' , __FUNCTION__ , "\n";
	}
}

Test::run();
$ php Test.php
run
App\Test::run
App\Test::run

2. 函数和闭包

<?php

namespace App;

function test() {
	echo __FUNCTION__ , "\n";
	echo __METHOD__ , "\n";
}

$closure = function() {
	echo __FUNCTION__ , "\n";
	echo __METHOD__ , "\n";
};

test();
$closure();
$ php Test.php
App\test
App\test
App\{closure}
App\{closure}

3. 继承和Trait

<?php

namespace App;

class Papa {
	public static function test() {
		echo __FUNCTION__ . "\n";
		echo __METHOD__ , "\n";
		echo __CLASS__ , '::' , __FUNCTION__ , "\n";
	}
}

trait Mama
{
	public static function test() {
		echo __FUNCTION__ . "\n";
		echo __METHOD__ , "\n";
		echo __CLASS__ , '::' , __FUNCTION__ , "\n";
	}
}


class Test extends Papa {

	use Mama;

	public static function run() {
		parent::test();
		self::test();
	}
}

Test::run();
$ php Test.php
test
App\Papa::test
App\Papa::test
test
App\Mama::test
App\Test::test

总结

最后简单的总结一下:

不在 Class 里面__FUNCTION__ = __METHOD__
在 Class 里面(don‘t use trait)__CLASS__ . “::” . __FUNCTION__ = __METHOD__
在 Class 里面(use trait)只有 __METHOD__ 的结果是正确的。

所以不管什么情况,用 __METHOD__ 就对了。


参考:

http://php.net/manual/en/language.constants.predefined.php

492 total views, 5 views today