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

问题描述

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

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

私有函数parentmethod($ arg2){
// do something ..
}
}

class B extends A {
function __construct($ arg){
parent :: __ construct arg);
}
function childfunction(){
echo parent :: $ bb; //致命错误:未定义的类常量'bb'
}
}

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

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

解决方案



  echo $ this-> bb; 

该变量是继承的,不是私有的,因此它是当前对象的一部分。 p>




这是响应您的请求的其他信息,了解有关使用 parent ::



当您需要添加额外功能时,使用 parent :: 到父类的方法。例如,假设一个 Airplane 类:

  class Airplane {
private $ pilot;

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

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

  class Bomber extends Airplane {
private $ navigator;

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

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

以这种方式,您可以遵循的开发,但仍然提供您所需的所有功能。 / p>

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();

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.


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

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;
    }
}

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
    }
}

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

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

09-01 19:43