如果类像这样在一个文件中,似乎不会发生严格错误:
abstract class Food{}
class Meat extends Food{}
abstract class Animal{
function feed(Food $food){ }
}
class Cat extends Animal{
function feed(Meat $meat){
parent::feed($meat);
}
}
但是如果您将类定义放在单独的文件中并像这样包含它们:
abstract class Food{}
class Meat extends Food{}
require 'Animal.php';
require 'Cat.php';
抛出严格标准错误信息:
Strict standards: Declaration of
Cat::feed()
should be compatible withAnimal::feed(Food $food)
in c:\path\to\Cat.php on line...
如果所有内容都在一个文件中,即使这样也没关系:
class Dog extends Animal{
function feed($qty = 1){
for($i = 0; $i < $qty; $i++){
$Meat = new Meat();
parent::feed($Meat);
}
}
}
这是预期的行为吗?
因为 Meat
是一种 Food
,所以一开始就不应该提示,对吧?
所以解决方案简单明了:将所有内容放在一个文件中并满足严格的标准;)
感谢任何提示
最佳答案
Is this the intended behavior?
不幸的是,是的。类声明的复杂性使得当它们都出现在同一个脚本中时,并不总是应用严格的规则;每个文件一个类不会出现此问题。
Because Meat is a Food, there shouldn't be a complain in the first place, right?
错误的原因有两个:
Meat 是比 Food 更小的类型,因此在您的后代类中只允许使用更小的类型,您违反了 LSP ;你不能用
Cat
代替Animal
。在 PHP 中,参数类型是 invariant重载方法时,即接受的类型必须与父类的类型完全匹配。虽然可以说逆变类型是有意义的,但由于技术原因,这是不可能的。
So the solution is plain and clear: Put everything in one file and strict standards are satisfied ;)
不,你绝对不应该依赖这种行为。
关于包含 php 严格错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30644416/