我有一个关于 PHP 从子类中的父级调用函数的技巧问题。我们有 3 个场景,我想要优点和缺点。
<?php
class test{
private $var ;
public function __construct(){
$this->var = 'Hello world';
}
public function output(){
echo $var.'<br>';
}
}
//scenario 1
class test1 extends test{
public function __construct(){
parent::__construct();
}
public function say(){
parent::output();
}
}
//scenario 2
class test2 extends test{
public function __construct(){
test::__construct();
}
public function say(){
test::output();
}
}
//scenario 3
class test3 extends test{
private $handle ;
public function __construct(){
$this->handle = new test();
}
public function say(){
$this->handle->output();
}
}
//finally I can call any 3 cases by one of the below codes
$test1 = new test1();
$test1->say();
//or
$test2 = new test2();
$test2->say();
//or
$test3 = new test3();
$test3->say();
?>
是否有最佳实践,或者这 3 种方案中是否有任何一种比其他方案更好?
先感谢您。