在php中继承属性 [英] inheriting properties in php

查看:213
本文介绍了在php中继承属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超类,其中包含属性&设置方法

I have a superclass which contains properties & methods for setting them

class Super{
    private $property;

    function __construct($set){
        $this->property = $set;
    }
}

然后我有一个需要使用该属性的子类

then I have a subclass that needs to use that property

class Sub extends Super{
    private $sub_property

    function __construct(){
        parent::__construct();
        $this->sub_property = $this->property;
    }
}

但我不断收到错误消息

Notice: Undefined property: Sub::$property in sub.php on line 7

我要去哪里错了?

推荐答案

错误是说它正在尝试查找不存在的名为$ property的局部变量.

The error is saying that it's trying to find a local variable called $property which doesn't exist.

要按预期在对象上下文中引用$ property,您需要$this和箭头.

To refer to $property in object context, as you intended, you need $this and the arrow.

$this->sub_property = $this->property;

其次,上面的行将按原样失败,因为$propertySuper类的private.改为protected,即可继承.

secondly, the line above will fail as is because $property is private to the Super class. Make it protected instead, so it's inherited.

protected $property;

第三,(感谢Merijn,我错过了),Sub需要扩展Super.

Third, (thanks Merijn, I missed this), Sub needs to extend Super.

class Sub extends Super

这篇关于在php中继承属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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