vendredi 28 avril 2017

Applying polymorhism in PHP to remove if-else statement

Reading about PHP, OOP and polymorphism, i have seen many discussions about if-else replacement with polymorphism. In this question Deserializing from JSON into PHP, with casting?, the highest voted answer has the following code:

class User
{
   public $username;
   public $nestedObj; //another class that has a constructor for handling json
   ...

   // This could be make private if the factories below are used exclusively
   // and then make more sane constructors like:
   //     __construct($username, $password)
   public function __construct($mixed)
   {
       if (is_object($mixed)) {
           if (isset($mixed->username))
               $this->username = $mixed->username;
           if (isset($mixed->nestedObj) &&     is_object($mixed->nestedObj))
           $this->nestedObj = new NestedObject($mixed->nestedObj);
       ...
       } else if (is_array($mixed)) {
           if (isset($mixed['username']))
               $this->username = $mixed['username'];
           if (isset($mixed['nestedObj']) && is_array($mixed['nestedObj']))
               $this->nestedObj = new NestedObj($mixed['nestedObj']);
           ...
       }
   }
   ...

   public static fromJSON_by_obj($json)
   {
       return new self(json_decode($json));
   }

   public static fromJSON_by_ary($json)
   {
       return new self(json_decode($json, TRUE)); 
   }
}

My question is nothing related to the mentioned question or the code. What I want to know is, in the above class, instead of using if else in the constructor, can we apply polymorphism to remove the if else. I don't want to know whether it is efficient or good practice. I just want to see how it is done.

Aucun commentaire:

Enregistrer un commentaire