i want to show a name.name may be in uppercase or in lowercase this will be depend on which class i will pass.i have to approach one is using class
and second is interface
which one is better and why ?
Solution using Class
class User{ } class Iuser extends User{ private $name; function __construct($name){ $this->name = $name; } function getName(){ return strtoupper($this->name); } } class Wuser extends User{ private $name; function __construct($name){ $this->name = $name; } function getName(){ return strtolower($this->name); } } class Name{ public $u; function __construct(User $u){ $this->u = $u; } function getName(){ $name = $this->u->getName(); return "Hi My Name is ".$name; } } $name = "Deval Patel"; $iu = new Iuser($name); $wu = new Wuser($name); $user = new Name($wu); echo $user->getName();
Solution Using Interface
interface User{ public function getName(); } class Iuser implements User{ private $name; function __construct($name){ $this->name = $name; } function getName(){ return strtoupper($this->name); } } class Wuser implements User{ private $name; function __construct($name){ $this->name = $name; } function getName(){ return strtolower($this->name); } } class Name{ public $u; function __construct(User $u){ $this->u = $u; } function getName(){ $name = $this->u->getName(); return "Hi My Name is ".$name; } } $name = "Deval Patel"; $iu = new Iuser($name); $wu = new Wuser($name); $user = new Name($iu); echo $user->getName();