【发布时间】:2016-09-17 21:42:00
【问题描述】:
我想在父类构造中获取子类。问题是,我在 SO 中找到了几个 PHP 方法,不知道用哪个,哪个更快?
class Parent {
function __construct() {
echo static::class; // Method 1 (PHP 5.5+)
echo get_called_class(); // Method 2 (PHP 5.3+)
echo get_class($this); // Method 3 (PHP 5.2+)
}
}
class Child extends Parent {
function __construct() {
parent::__construct();
}
}
所有回显都写入相同的结果:Child。但是为什么相同的结果有 3 种不同的方法呢?哪个更好,或者更优化?
【问题讨论】:
-
你为什么不运行一些性能测试看看?
-
问题不只是关于性能,还有为什么有3种方法可以得到相同的结果,如果有其他区别的话。
-
get_class($this)可以调用传入任何对象的实例,包括(但不限于)$this;例如$x = 新日期时间(); echo get_class($x);; soget_class()` 是一个非常通用的函数,还有其他用途
标签: php class constructor