Reputation: 20369
I am confused what the difference or the performance gain would be between these 2 scenario's. Why would one be chosen over the other?
Parent class:
class exampleB
{
public function __construct($arg1, $arg2)
{
// Do something with the arguments.
}
}
Child class A
class exampleA extends exampleB
{
public function make($arg1, $arg2)
{
parent::__construct($arg1, $arg2);
}
}
Running the first example:
$exampleA = new exampleA();
$exampleA->make('arg1', 'arg2');
The second example would be:
Child class A
class exampleA extends exampleB
{
public static function make($arg1, $arg2)
{
return new static($arg1, $arg2);
}
}
Running the second example:
exampleA::make('arg1', 'arg2');
Could somebody tell me the advantages and/or disadvantages between these 2 scenarios? The reason I have these example because I do not want to override the constructor of my parent class.
Upvotes: 0
Views: 59
Reputation: 72729
You should do neither and use the constructor to initialize the object. The object must be in a valid state after construction.
The reason I have these example because I do not want to override the constructor of my parent class.
Then simply just don't define the constructor in the child class.
class Parent {
public function __construct() {
echo 'parent ctor called';
}
}
class Child extends Parent {}
new Child(); // echo's parent ctor called
Upvotes: 2
Reputation: 2641
I would opt for the second example. Make() acts like a constructor and thus should be called like one, i.e. static.
In the first example you create two objects instead of one. This might create some confusion when other devs read / mantain your code.
Upvotes: -1