Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php构造函数中的父/子类型暗示?_Php_Oop_Inheritance_Php 5.2 - Fatal编程技术网

php构造函数中的父/子类型暗示?

php构造函数中的父/子类型暗示?,php,oop,inheritance,php-5.2,Php,Oop,Inheritance,Php 5.2,在不讨论我是否应该使用类型暗示的情况下,有没有人能告诉我,当我将一个子类传递给一个为父类提供类型暗示的构造函数时,是否有办法避免PHP抛出错误?例如: class Headed extends Image { ... } class Dimension { function __construct(Image $image, $arg1, $arg2){ ... } } PHP给了我: PHP Error 4096: Argument 1 passed to Dimension::_

在不讨论我是否应该使用类型暗示的情况下,有没有人能告诉我,当我将一个子类传递给一个为父类提供类型暗示的构造函数时,是否有办法避免PHP抛出错误?例如:

class Headed extends Image { ... }

class Dimension {
    function __construct(Image $image, $arg1, $arg2){ ... }
}
PHP给了我:

PHP Error 4096: Argument 1 passed to Dimension::__construct() must be an instance of Image, instance of Headed given
类型为Headed的对象显然也是一个映像,因为它是一个子类,是否有某种方式来表达我的构造函数,使它给出类型提示但允许子类


如果这是因为我使用了PHP5.2.5而不是最新版本,我很抱歉打扰了大家。

使用
PHP5.4.3

我运行这个代码

<?php

class Image {
public $a="s";
};

class Headed extends Image { };

class Dimension {
    function __construct(Image $image) 
    {
        var_dump($image);
    }
};

$h = new Headed;
$d = new Dimension($h);

?>

在此处测试您的代码:。它会告诉你这是否是一个版本问题。也许如果你有一个接口,比如说“ImageInterface”,你有类Image实现ImageInterface,这样你就可以用Image而不是ImageInterface来提示了?我使用了3v4l.org,就像@johncode建议的那样,它对我有效:(在所有PHP5.x版本上)这不应该是这种情况。类的类型提示也显式地允许该类的子类型,这是OOP的核心思想之一。要么你在旧版本中发现了一个模糊的bug,要么你没有正确地测试它(输入错误?)。谢谢大家的评论-我认为这是错误的,但我不确定。我在你建议的网站上尝试了我的完整代码,发现facepalm的图片扩展了引用,产品扩展了引用,标题扩展了产品。。。所以我需要键入提示以供参考(祖父母类)。很抱歉给您添麻烦,谢谢大家帮我清理!
object(Headed)#1 (1) { ["a"]=> string(1) "s" }