如何确保子方法实例化的是子对象而不是父对象?

问题描述 投票:0回答:1

我有一个父类和一个子类,如下所示。

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 {
    // 
}

当我调用方法 Produit::findByNumeroDeSerie($table, $numeroDeSerie),

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

它实例化了一个 Objet 而非 Produit的getter方法,这意味着我不能访问 Produit 的实例化对象上。

知道为什么吗?我是否需要重写 findByNumeroDeSerie 方法在Objet的每个子类中?

php oop parent-child
1个回答
0
投票

你写的。

return new Objet($row);

所以你有Object。如果你想 findByNumeroDeSerie 返回产品使用 get_called_class() 这样的功能。

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

1
投票

简单多了,只要用 static 和"迟到的静态约束力".

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

产量:

儿童

父母

© www.soinside.com 2019 - 2024. All rights reserved.