2015-01-09 63 views
1

我结束了几次解决方案,其中有两个类的层次结构。来自第一个(Greeters)hiearchy的类使用第二个(用户)的类。覆盖方法从派生子类获取参数

继承人例如:

class User {} 
class Admin extends User { 
    function getSecretMessage() { 
     return "secret"; 
    } 
} 

class Greeter { 
    public function hello(User $a) { 
     echo "hello!"; 
    } 
} 

class AdminGreeter extends Greeter { 
    public function hello(Admin $a) { 
     parent::hello($a); 
     echo "in addition heres a secret of mine: " . $a->getSecretMessage(); 
    } 
} 

在这里,我有用户和招待员的,在PHP中我收到错误(严格)

“AdminGreeter声明::你好必须与迎宾::兼容你好“

我希望AdminGreeter::hello简单地使用来自更专门化类(Admin)的数据”扩展“Greeter::hello

我还有什么替代方案可以构建类似的PHP?

我想主要的问题是,PHP不支持“方法重载”,从而如果我发送一个User实例到AdminGreeter它会中断。但是如果我有“方法重载”,Greeter::hello只会传递给用户实例。

这可能是一个总体上不好的设计,因为我最终遇到了这个问题,也许有人可以指出我对这个问题有更好的设计。

正如我旁注我似乎有同样的问题,发展中的Objective-C

+1

'Admin'不是一个类,它是一个[接口](http://php.net/manual/en/language.oop5.interfaces.php) – 2015-01-09 21:28:37

+0

谢谢你的权利,我应该适当地使用措辞“类型“而不是”类“。我编辑的问题,以消除任何混淆:) – 2015-01-09 21:34:18

+0

可能重复的[PHP的接口继承 - 声明必须兼容](http://stackoverflow.com/questions/19131157/php-interface-inheritance-declaration-must-be-兼容) – 2015-01-09 21:34:54

回答

0

也许当你可以考虑使用Traits而不是为这些“特殊班”

class User { 
    protected $name; 
    public function __construct($name) { 
     $this->name = $name; 
    } 
    public function __toString() { 
     return $this->name; 
    } 
} 

trait Admin { 
    function getSecretMessage() { 
     return "secret"; 
    } 
} 

class Greeter { 
    public function hello(User $a) { 
     echo "Hello ", $a, "!", PHP_EOL; 
    } 
} 

class AdminGreeter extends Greeter { 
    use Admin; 
    public function hello(User $a) { 
     parent::hello($a); 
     echo "in addition heres a secret of mine: " . $this->getSecretMessage(); 
    } 
} 

$x = new User('Natalie'); 
$y = new AdminGreeter; 
$y->hello($x); 
0

要继续与原始代码尽可能多:

interface iUser { 
    public function getSecretMessage(); 
} 

class Admin implements iUser { 
    function getSecretMessage() { 
     return 'secrete'; 
    } 
} 

class Greeter implements iUser{ 
    public function hello(iUser $a) { 
     echo 'hello'; 
    } 

    public function getSecretMessage(){} 
} 

class AdminGreeter extends Greeter { 
    public function hello(iUser $a) { 
     parent::hello($a); 
     echo ' in addition heres a secrete of mine: ' . $a->getSecretMessage(); 
    } 
} 

AdminGreeter::hello(new Admin); 

输出hello in addition heres a secrete of mine: secrete