由父节点和子节点共同构建


construct by both parent and child

我想在php中做这样的事情:我想有父类命名为"项目",和一堆子类,如"剑","盔甲"等。我可以简单地调用:

$some_sword = new sword($id) ;

但是我也想这样做:

$some_sword = new item("sword",$id) ;

我希望两个代码都有相同的效果。$some_sword在两个方面必须是相同的类!

new关键字将始终返回所讨论的类的实例。然而,你可以在父类中使用静态方法来返回子类对象(或任何与此相关的对象)。

class Item
{
    public function __construct($id)
    {
        //Whatever
    }
    /**
     * Gets the object requested and passes the ID
     *
     * @param string object to return
     * @param integer id
     * @return object
     */
    public static function get($itemtype, $id)
    {
        $classname = ucfirst($itemtype);
        return new $classname($id);
    }
}
class Sword extends Item
{
    public function __construct($id)
    {
        //Whatever
    }
}
class Armor extends Item
{
    public function __construct($id)
    {
        //Whatever
    }
}
// Client Code
$some_sword = Item::get('sword', 1);
$some_armor = Item::get('armor', 2);