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 ?
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"