2013-04-27 115 views
1

我想在php中制作这样的东西: 我想让父类名为“item”,并且有一堆儿童类,比如“剑”,“护甲”等。 我可以简单地叫:php - 由父母和孩子构建

$some_sword = new sword($id) ; 

但我也想做某事像这样:

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

而且我想这两个代码做他同样的效果。 $ some_sword在两种方式中必须是相同的类!

回答

3

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); 
+0

编辑以修复get方法错误(!我之前,我将它张贴真的应该测试我的代码) – 2013-04-27 17:44:37

+0

谢谢,这似乎是不够的适用:d – 2013-04-28 01:31:46

+0

你觉得你可能使它的接受回答?这将意味着很多:) – 2013-04-29 10:40:16