由於PHP 5.3.3,我有5.6和7.0測試此,聲明類final
的__construct
方法將防止任何兒童類中重寫或者使用__construct
或ClassName()
的PHP 4的風格構造(注意,自PHP 7起,PHP 4風格已棄用)。防止聲明構造函數的子類將確保始終調用父構造函數。這當然不會允許任何子類實現自己的構造函數邏輯。雖然我不會推薦它作爲一般的良好實踐,但肯定會有實際用例。
一些例子:
不宣__construct
最終
class ParentClassWithoutFinal {
private $value = "default";
public function __construct() {
$this->value = static::class;
}
function __toString() {
return $this->value;
}
}
class ChildClassA extends ParentClassWithoutFinal {
public function __construct() {
// Missing parent::__construct();
}
}
echo (new ChildClassA()); // ouput: default
隨着最後__construct
class ParentClassWithFinal extends ParentClassWithoutFinal {
public final function __construct() {
parent::__construct();
}
}
class ChildClassB extends ParentClassWithFinal {
}
echo (new ChildClassB()); // output: ChildClassB
試圖在一個子類來聲明__construct
class ChildClassC extends ParentClassWithFinal {
public function __construct() {
}
}
// Fatal error: Cannot override final method ParentClassWithFinal::__construct()
試圖在一個子類
class ChildClassD extends ParentClassWithFinal {
public function ChildClassD() {
}
}
// Fatal error: Cannot override final ParentClassWithFinal::__construct() with ChildClassD::ChildClassD()
// Also in PHP 7: Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; ChildClassD has a deprecated constructor
我明白你爲什麼不信任PHP程序員申報
ClassName()
構造函數,但我不明白爲什麼你關心:-) – 2010-01-03 03:28:41我只是想要明確我的代碼 – 2010-01-03 10:56:02