0

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.

Stephan-v
  • 19,255
  • 31
  • 115
  • 201
  • 2
    I wouldn't use either, `$exampleA = new exampleA('arg1', 'arg2');` is all you need as the constructor in `exambleB` will be called automatically as long as you don't overwrite it. – jeroen Nov 18 '16 at 11:00
  • I don't want to override the existing constructor in my parent class that's why I came up with these solutions. Should have added that. – Stephan-v Nov 18 '16 at 11:11

2 Answers2

2

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
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
-1

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.

Markus Müller
  • 2,611
  • 1
  • 17
  • 25