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

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

问题描述

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

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

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

但我不确定多态性.我在网上搜索到了这个:

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 支持多态 旁边放置一个明确的是"或否".我不愿意说: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天全站免登陆