PHP 访问父类变量 [英] PHP Accessing Parent Class Variable

查看:37
本文介绍了PHP 访问父类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {
    private $aa;
    protected $bb = 'parent bb';

    function __construct($arg) {
       //do something..
    }

    private function parentmethod($arg2) {
       //do something..
    }
}

class B extends A {
    function __construct($arg) {
        parent::__construct($arg);
    }
    function childfunction() {
        echo parent::$bb; //Fatal error: Undefined class constant 'bb' 
    }
}

$test = new B($some);
$test->childfunction();

问题:如何在孩子中显示父变量?预期结果将回显 'parent bb'

Question: How do I display parent variable in child? expected result will echo 'parent bb'

推荐答案

echo $this->bb;

变量是继承的,不是私有的,所以是当前对象的一部分.

The variable is inherited and is not private, so it is a part of the current object.

以下是应您要求提供有关使用 parent:: 的更多信息的附加信息:

Here is additional information in response to your request for more information about using parent:::

当您希望向父类中的方法添加额外功能时,请使用parent::.例如,想象一个 Airplane 类:

Use parent:: when you want add extra functionality to a method from the parent class. For example, imagine an Airplane class:

class Airplane {
    private $pilot;

    public function __construct( $pilot ) {
        $this->pilot = $pilot;
    }
}

现在假设我们要创建一种也有导航器的新型飞机.您可以扩展 __construct() 方法以添加新功能,但仍可使用父级提供的功能:

Now suppose we want to create a new type of Airplane that also has a navigator. You can extend the __construct() method to add the new functionality, but still make use of the functionality offered by the parent:

class Bomber extends Airplane {
    private $navigator;

    public function __construct( $pilot, $navigator ) {
        $this->navigator = $navigator;

        parent::__construct( $pilot ); // Assigns $pilot to $this->pilot
    }
}

通过这种方式,您可以遵循DRY原则的开发,但仍然提供所有您想要的功能.

In this way, you can follow the DRY principle of development but still provide all of the functionality you desire.

这篇关于PHP 访问父类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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