phpoopinheritanceextendslate-static-binding

Difference between these two OOP scenarios?


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.


Solution

  • 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