为什么可以在PHP中覆盖实例变量而不是在Java中? [英] Why is it possible to override instance variables in PHP but not in Java?

查看:113
本文介绍了为什么可以在PHP中覆盖实例变量而不是在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

<?php

class Base {
        protected $name = "Base";

        public function getName() {
            return $this->name;
        }
}

class Foo extends Base {
        protected $name = "Foo";
}

$f = new Foo();
echo $f->getName(); // output: Foo

$b = new Base();
echo $b->getName(); // output: Base

因为Java之类的其他语言不允许你覆盖实例变量,但在PHP中是可能的。

Since in other languages such as Java won't allow you to override the instance variable, but it is possible in PHP.

是因为PHP是弱类型语言所以有可能吗?

Is it because since PHP is weak type language so it is possible?

推荐答案

不,它与弱打字无关

我想这只是PHP开发人员的一个设计决策。这可能是因为它更像是一种脚本语言而不是Java。 (在Java中,您需要为字段提供虚拟查找表以支持此项,或者自动生成的getter / setter)。

I guess this was simply a design decision that the PHP developers took. It may be because it is more of a scripting language than Java. (In Java, you would need to have a "virtual" lookup table for fields to support this or, alternatively, automatically generated getters / setters).

这篇关于为什么可以在PHP中覆盖实例变量而不是在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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