Marty Wallace
Marty Wallace

Reputation: 35744

PHP - with and clone instead of constructor

I have seen code like the following a few times and cannot think what the reasonsing is:

public function withParameter($parameter)
{
    $clone = clone $this;
    $clone->parameter = $parameter;

    return $clone;
}

Also similar things:

public static function fromString(string $parameter)
{
    return new StringValueClass($parameter);
}

Why have a static function like this instead of just use the constructor?

Upvotes: 0

Views: 230

Answers (1)

Sahil Gulati
Sahil Gulati

Reputation: 15141

Function 1:

public function withParameter($parameter)
{
    $clone = clone $this;
    $clone->parameter = $parameter;
    return $clone;
}

This function is returning clone of current class object $this in which a parameter $clone->parameter is set. Here you can performed operation on object $clone which in return does not effect your current class object $this

Function 2:

public static function fromString(string $parameter)
{
    return new StringValueClass($parameter);
}

Here we are returning some other class object through this static function you can return an object but through __construct you can not, because does not return anything

Upvotes: 2

Related Questions