在PHP中看来多态真的是多态吗? [英] Is what seems like polymorphism in PHP really polymorphism?

查看:85
本文介绍了在PHP中看来多态真的是多态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图弄清楚PHP是否支持方法重载,继承和多态性等功能,我发现:

Trying to figure out whether PHP supports features like method overloading, inheritance, and polymorphism, I found out:

  • 它不支持方法重载
  • 它确实支持继承

但是我不确定多态性.我在Google上搜索了以下内容:

but I am unsure about polymorphism. I found this Googling the Internet:

我应该注意,在PHP中 多态并不完全是这样 应该.我的意思是它确实有效, 但由于我们的数据类型较弱,因此 不正确.

I should note that in PHP the polymorphism isn't quite the way it should be. I mean that it does work, but since we have a weak datatype, its not correct.

那真的是多态吗?

修改 只是不能在PHP supports polymorphism旁边放置确定的YES或NO.我不愿声明:"PHP不支持多态",但实际上却支持.反之亦然.

Edit Just can't quite place a definite YES or NO next to PHP supports polymorphism. I would be loath to state: "PHP does not support polymorphism", when in reality it does. Or vice-versa.

推荐答案

class Animal {
    var $name;
    function __construct($name) {
        $this->name = $name;
    }
}

class Dog extends Animal {
    function speak() {
        return "Woof, woof!";
    }
}

class Cat extends Animal {
    function speak() {
        return "Meow...";
    }
}

$animals = array(new Dog('Skip'), new Cat('Snowball'));

foreach($animals as $animal) {
    print $animal->name . " says: " . $animal->speak() . '<br>';
}

您可以随意标记它,但是对我来说,这看起来像是多态性.

You can label it all you want, but that looks like polymorphism to me.

这篇关于在PHP中看来多态真的是多态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆