包含 php 严格错误

标签 php strict

如果类像这样在一个文件中,似乎不会发生严格错误:

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 with Animal::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?

错误的原因有两个:

  1. Meat 是比 Food 更小的类型,因此在您的后代类中只允许使用更小的类型,您违反了 LSP ;你不能用 Cat 代替 Animal

  2. 在 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/

相关文章:

javascript - 传递给 setTimeout 的函数 fn 是否不是作为函数调用,而是作为类似 window.fn() 的方法调用?

PHP 5 禁用严格标准错误

php - 这可以写得更好吗? PHP代码

php - 博客无法正确排序

javascript - JS 严格模式 : Why does (only! ) Edge 在分配样式属性时提示

perl (Statistics::PCA): 不能使用字符串 ("0") 作为 ARRAY ref while "strict refs"

angular - 未捕获的语法错误 :\8 and\9 are not allowed in strict mode

html - PHP - DOM,从 html 中剥离表格

php - 适用于 Ubuntu 的 WYSIWYG Web 编辑器(php、CSS、HTML、Javascript)好吗?

php - 如何使用 PHP 从 <select> 中获取多个项目?