简体   繁体   English

家长在孩子最佳实践中的PHP调用函数

[英]PHP call function from parent in child best practice

I have a trick question regarding PHP calling a function from parent in child class. 我有一个关于PHP从子类的父类调用函数的技巧问题。 We have 3 scenarios, and I want pros and cons. 我们有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();
?>

Is there a best practice or is there any of the 3 scenarios better than other? 是否有最佳实践,或者这三种方案中的任何一种都比其他方案更好?

Thank you in advance. 先感谢您。

1) Is correct 1)是正确的

2) Is incorrect call the method like a static method. 2)不正确地调用该方法,就像静态方法一样。

3) It does not have any sense extend and create in the constructor. 3)它在构造函数中没有任何扩展和创建的意义。

1) This one is correct, as its calling the parent from its methods. 1)这是正确的,因为它从其方法中调用父对象。

class test1 extends test{
   public function __construct(){
    parent::__construct();
   }
   public function say(){
    parent::output();
   }
}

2) The inheritance in here is unnecessary. 2)这里的继承是不必要的。 If you choose this implementation, you must change both output and construct method to static. 如果选择此实现,则必须将output和构造方法都更改为静态。

//scenario 2
class test2 extends test{
   public function __construct(){
    test::__construct();
   }
   public function say(){
    test::output();
   }
}

3) The inheritance from here is also unnecessary. 3)从这里继承也是不必要的。 Note here you are using "component over inheritance" pattern which is a good practice as it provides more flexibility, but you must delete the "extends test". 请注意,此处使用的是“组件继承”模式,这是一个好习惯,因为它提供了更大的灵活性,但是您必须删除“扩展测试”。

//scenario 3
class test3 extends test{
    private $handle ;
    public function __construct(){
     $this->handle = new test();
    }
    public function say(){
     $this->handle->output();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM