Benoît
Benoît

Reputation: 360

How to make sure child method instantiates child instead of parent object?

I have a parent and a child class as below

class Objet {

    ../..

    static function findByNumeroDeSerie($table, $numeroDeSerie) {
        $db = new Db();
        $query = $db->prepare("SELECT * from $table WHERE numeroDeSerie = :numeroDeSerie");
        $query->bindValue(':numeroDeSerie', $numeroDeSerie, PDO::PARAM_INT);
        $query->execute(); 
        while($row = $query->fetch()) {
            return new Objet($row);
        }
    }
}


class Produit extends Objet {
    // 
}

When I call method Produit::findByNumeroDeSerie($table, $numeroDeSerie),

$produit = Produit::findByNumeroDeSerie("produits", $_GET['numeroDeSerie']);
echo get_class($produit); // echoes Object

it instantiates an Objet instead of a Produit, which means I can't access the getter methods of Produit on the instantiated object.

Any idea why? Do I need to rewrite the findByNumeroDeSerie method in every child class of Objet ?

Upvotes: 0

Views: 44

Answers (2)

yivi
yivi

Reputation: 47657

Much simpler, just use static and "late static binding".

class TheParent {

    public static function build(): TheParent
    {
        return new static();
    }
}

class Child extends TheParent {}

$child = Child::build();
$parent = TheParent::build();

echo get_class($child), "\n"; //
echo get_class($parent), "\n";

Output:

Child

TheParent

Upvotes: 1

Nolifer
Nolifer

Reputation: 94

You wrote:

return new Objet($row);

So you have Object. If you want findByNumeroDeSerie to return Product use get_called_class() function like this:

<?php

class A {
    static public function foo() {
        $className = get_called_class();
        return new $className();
    }
}

class B extends A {

}

var_dump(get_class(B::foo())); // string(1) "B"

Upvotes: 0

Related Questions