【发布时间】:2016-09-25 08:56:58
【问题描述】:
我想显示一个名字。名字可能是大写或小写,这取决于我将通过哪个类。我必须接近一个使用class,第二个是interface 哪个更好,为什么?
-
使用类的解决方案
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(); -
使用接口的解决方案
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();
【问题讨论】:
-
为什么要创建一个空类来扩展它?
-
@VasilShaddix 不扩展类如何将任何对象传递给 Name CLass
标签: php class interface extends implements