简体   繁体   中英

PHP call function from parent in child best practice

I have a trick question regarding PHP calling a function from parent in child class. We have 3 scenarios, and I want pros and cons.

<?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

2) Is incorrect call the method like a static method.

3) It does not have any sense extend and create in the constructor.

1) This one is correct, as its calling the parent from its methods.

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

2) The inheritance in here is unnecessary. If you choose this implementation, you must change both output and construct method to static.

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

3) The inheritance from here is also unnecessary. 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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