0

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 ?

yivi
  • 42,438
  • 18
  • 116
  • 138
Benoît
  • 360
  • 2
  • 14
  • There's no way for the instantiation to be dynamic ? the code of the child method will be identical to the parent, it seems like it would defeat the purpose of parent and child :) – Benoît May 15 '20 at 16:34
  • I've edited the end of my question to explain better (so you can understand where I'm trying to instantiate a Produit – Benoît May 15 '20 at 16:38

2 Answers2

1

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

Community
  • 1
  • 1
yivi
  • 42,438
  • 18
  • 116
  • 138
0

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"
Nolifer
  • 84
  • 5