How to autostart a construct in a parent class without calling from a child class

I am looking for a way to call the constructor of the parent class (?) Automatically-magically from the child class:

(Note: this is just an example, so input errors may occur)

Class myParent() { protected $html; function __construct( $args ) { $this->html = $this->set_html( $args ); } protected function set_html( $args ) { if ( $args['foo'] === 'bar' ) $args['foo'] = 'foobar'; return $args; } } Class myChild extends myParent { public function do_stuff( $args ) { return $this->html; } } Class myInit { public function __construct( $args ) { $this->get_stuff( $args ); } public function get_stuff( $args ) { $my_child = new myChild(); print_r( $my_child->do_stuff( $args ) ); } } $args = array( 'foo' => 'bar, 'what' => 'ever' ); new myInit( $args ); // Should Output: /* Array( 'foo' => 'foobar', 'what' => 'ever' ) */ 

What I want to avoid is to call (inside the myChild class) __construct( $args ) { parent::__construct( $args ); } __construct( $args ) { parent::__construct( $args ); } .

Question: Is this possible? If yes: How?

Thanks!

+6
source share
2 answers

In your code example, myParent :: __ construct will already be called by wen instanciating myChild. To make your code work the way you want, just change

 public function get_stuff( $args ) { $my_child = new myChild(); print_r( $my_child->do_stuff( $args ) ); } 

  public function get_stuff( $args ) { $my_child = new myChild($args); print_r( $my_child->do_stuff() ); } 

As long as myChild does not have a constructor , the parent constructor will be called / inherited.

+9
source

Since Child does not have a constructor and extends Parent , at any time new Child() indicates the Parent constructor will be implicit .

If you specify a Child constructor, then you need to use define parent::__construct(); inside the Child constructor as it will not be called implicitly.

NB When defining a constructor in a subclass, it is best to call parent::__construct() on the first line of the method definition so that all instance parameters and state inherited are set before the subclass starts.

+5
source

Source: https://habr.com/ru/post/891127/


All Articles