I'm searching for a way to call a parent class constructor(?) auto-magically from a child class:
(Note: This is just an example, so typing errors may be present)
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 having to call (inside Class myChild) __construct( $args ) { parent::__construct( $args ); }
.
Question: Is this possible? If so: How?
Thanks!
Case1. We can't run directly the parent class constructor in child class if the child class defines a constructor.
Answer: Yes,It is possible, 1) If it is a static method.
Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type. If we define Parent class constructor inside Child class it will give compile time error for return type and consider it a method.
In your sample code, myParent::__construct will already get called wen instanciating myChild. To get your code to work as you want simply change
public function get_stuff( $args )
{
$my_child = new myChild();
print_r( $my_child->do_stuff( $args ) );
}
by
public function get_stuff( $args )
{
$my_child = new myChild($args);
print_r( $my_child->do_stuff() );
}
As long as myChild has no constructor, the parent constructor will be called / inherited.
As Child
has no constructor present and extends Parent
, any time new Child()
is specified the Parent
constructor will be implicitly called.
If you do specify a Child
constructor then you have to use specify parent::__construct();
inside the Child
constructor as it will not be called implicitly.
N.B When defining a constructor in a subclass it is best practice to call parent::__construct()
on the first line of the method definition so that any instance parameters and state inherited is set prior to subclass initiation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With