如何从孩子那里获得父母覆盖的财产? [英] how to get to parent overridden property from child?

查看:49
本文介绍了如何从孩子那里获得父母覆盖的财产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 php 文档中它说:

in the php documentation it says:

范围解析运算符(也称为 Paamayim Nekudotayim)或在更简单的术语,双冒号,是一个令牌,允许访问类的静态、常量和覆盖的属性或方法.

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

当我尝试访问被覆盖的(非静态)父属性时出现错误:

i get an error when i try to access overridden (not static) parent properties:

class foo
{
    public $bar = 'foobar';
}

class baz extends foo
{
    public $bar = 'bazbar';

    public function get_bar()
    {
        echo parent::$bar; //Fatal error:  Access to undeclared static property: foo::$bar
    }
}

$baz = new baz;
$baz->get_bar();

推荐答案

Fisrt,将 :: 与静态属性一起使用,而不是实例属性.
其次,虽然你可以用反射来做到这一点(见下面的代码),但我看不到访问父实例属性的任何点,这是 polymorphism 的目的.

Fisrt, use :: with static properties, not instance properties.
Second, though you can do it with Reflection(see the following code), I don't see any point accessing parent instance properties, that's polymorphism is for.

class foo
{
    public $bar='foobar';
}
class bar extends foo
{
    public $bar='bazbar';
    function get_bar()
    {
        $thisClass = new ReflectionClass($this);
        $parentClass = $thisClass->getParentClass();
        $props = $parentClass->getDefaultProperties();
        return $props['bar'];
    }
}

$b = new bar();
echo $b->get_bar(); // foobar

这篇关于如何从孩子那里获得父母覆盖的财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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