【问题标题】:Is there any way to access Base Class Property via Derived Class object directly in PHP有没有办法直接在 PHP 中通过派生类对象访问基类属性
【发布时间】:2013-06-05 12:39:26
【问题描述】:

在php中,有没有办法直接通过派生类类型的对象直接访问任何基类属性。

例如:

class a  
{  
    public $name="Something"; 

    function show()
    {
        echo $this->name;
    }
}; 
class b extends a  
{  
     public $name="Something Else";  

     function show()
     {
         echo $this->name;
     }
};

$obj = new b();
$obj->show();

它会打印字符串“Something Else”,但是如果我想访问基类函数显示呢,

它似乎不像在 c++ 中那样工作

obj.a::show();  

【问题讨论】:

  • 不,这在 PHP 中是不可能的。

标签: php class base derived


【解决方案1】:

由于您在子级中覆盖$name,因此该属性将具有子级的属性值。然后您无法访问父值。任何其他方式都没有任何意义,因为该属性是公共的,这意味着该属性对孩子(以及外部)可见,并且对其进行修改将改变基本值。因此,对于该实例而言,它实际上是一个且相同的属性和值。

拥有两个不同的同名属性的唯一方法是将基属性声明为私有,将子属性声明为非私有,然后调用可以访问基属性的方法,例如

class Foo
{
    private $name = 'foo';

    public function show()
    {
        echo $this->name;
    }
}

class Bar extends Foo
{
    public $name = 'bar';

    public function show()
    {
        parent::show();
        echo $this->name;
    }
}

(new Bar)->show(); // prints foobar

由于您的 C++ 示例调用使用的是 scope resolution operator ::,您可能正在寻找 class/static properties

class Foo
{
    static public $name = 'foo';

    public function show()
    {
        echo static::$name; // late static binding
        echo self::$name;   // static binding
    }
}

class Bar extends Foo
{
    static public $name = 'bar';

    public function show()
    {
        parent::show(); // calling parent's show()
        echo parent::$name; // calling parent's $foo
    }
}

(new Bar)->show(); // prints barfoofoo

【讨论】:

  • 感谢您的快速回复.. !!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 2020-09-23
  • 2022-11-23
  • 1970-01-01
相关资源
最近更新 更多