Search code examples
phpparent-childsubclassparentconstruct

php - construct by both parent and child


I want to make such thing in php: I want to have the parent class named "item", and a bunch of child classes like "sword", "armor" etc. I can call simply:

$some_sword = new sword($id) ;

But I also want to do sth like this:

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

And I want both codes do he same effect. $some_sword must be the same class in both ways!


Solution

  • the new keyword will always return an instance of the class in question. however you can use a static method in the parent to return child class object (or any objects for that matter).

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