Warning: Declaration of Wanter::create($b) should be compatible with Generic::create($a, $b) in [...][...] on line 25 I need coffee!I want coffee!很明显这应该做什么(正如它所做的那样).但是,我当然想在不发出警告的情况下运行它.如何在没有警告的情况下实现这一点?It is obvious what this should do (as it does). However I want to run this without throwing warnings of course. How to implement this without warning?推荐答案这应该是显而易见的,但是子方法定义必须与父方法定义匹配,因此您缺少一个参数.It should be obvious but the child method definition must match that of the parent, so you are missing an argument.我要做的是:class Generic { protected $a; protected $b; protected final function __construct($a,$b) { $this->a = $a; $this->b = $b; echo $this->a." ".$this->b; } public static function create($a,$b) { return new self($b,$a); //reverse arguments }}class Wanter extends Generic { public static function create($a, $b="I want") { return parent::create($b,$a); }}注意我改变了参数的顺序,这样默认的就是第二个参数.Note that I changed the order of the arguments, this way the one with the default is the second argument.您可以只在子类中执行此操作,但如果顺序与父类不同,则可能会有些混乱.You could do this just in the child, but it might be somewhat confusing, if the order is different then the parent class.也就是说,在这种情况下,工厂方法之类的东西可能更合适.That said, something like a factory method may be more appropriate in this instance.https://en.wikipedia.org/wiki/Factory_(object-oriented_programming)"面向编程)除了工厂模式之外,我不确定拥有静态 Create 方法对您来说有多重要.当需要多态之类的东西时,构造函数提供了更大的灵活性.例如这样的事情是可以接受的Besides a factory pattern I am not sure how important it is for you to have the static Create method. The constructor offers more flexibility when needing things like polymorphism. For example something like this would be acceptableabstract class Generic { protected $a; protected $b; protected function create($a,$b) { $this->a = $a; $this->b = $b; echo $this->a." ".$this->b; }}class Wanter extends Generic { public function __construct($a) { return $this->create("I want",$a); }}然后每个孩子都可以定义自己的构造函数,并带有自己的一组必需参数.Then each child can define it's own constructor, with its own set of required arguments. 这篇关于如何解决子类中的方法重载(...的声明应该与 兼容)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!