Php 如何使用依赖项注入与多个对象交互?

Php 如何使用依赖项注入与多个对象交互?,php,oop,dependency-injection,abstract-class,Php,Oop,Dependency Injection,Abstract Class,给出此代码: Animal.php Wolf.php index.php 我的问题是,狼可以伤害老虎,因为他的代码,但我不能伤害狗,因为我只需要在参数上指定一个类和对象。有没有办法与老虎和狗这两个班级互动? 以下是错误: Catchable fatal error: Argument 1 passed to Wolf::hurt() must be an instance of Tiger, instance of Dog given 谢谢如果不想将参数限制为单个类,则应删除函数中的类型提示

给出此代码:

Animal.php Wolf.php index.php 我的问题是,狼可以伤害老虎,因为他的代码,但我不能伤害狗,因为我只需要在参数上指定一个类和对象。有没有办法与老虎和狗这两个班级互动? 以下是错误:

Catchable fatal error: Argument 1 passed to Wolf::hurt() must be an instance of Tiger, instance of Dog given

谢谢

如果不想将参数限制为单个类,则应删除函数中的类型提示

下面是一个使用函数检索
$animal
类名称以实现所需效果的示例:

class Wolf extends Animal{
    public function hurt($animal) {
        // If animal is a tiger.
        if (get_class($animal) === 'Tiger') {
            $animal->setHealth(80);
        }
        // If animal is a dog.
        if (get_class($animal) === 'Dog') {
            $animal->setHealth(50);
        }
}

我对PHP不是很熟悉,但我在这里没有看到任何依赖注入,除非它与我预期的非常不同。你本可以用一个类型animal代替类型tigerI,但在你的例子$animal中,我不能用相同的名称从不同的类创建多个实例。@Schwarzenegger我创建了一个我从你的代码中理解的要点。我也给出了程序的输出。
class StackOverflowExample{
        public static function run(){

            $dog = new Dog("Cokey",100);
            $wolf = new Wolf("Wolfenstein",100);
            $tiger = new Tiger("Rocky",100);

            $wolf->hurt($tiger);
            echo $tiger->getHealth();

            $wolf->hurt($dog);
            echo $dog->getHealth();
        }
    }
    StackOverflowExample::run();
Catchable fatal error: Argument 1 passed to Wolf::hurt() must be an instance of Tiger, instance of Dog given
class Wolf extends Animal{
    public function hurt($animal) {
        // If animal is a tiger.
        if (get_class($animal) === 'Tiger') {
            $animal->setHealth(80);
        }
        // If animal is a dog.
        if (get_class($animal) === 'Dog') {
            $animal->setHealth(50);
        }
}