首页 > 解决方案 > 如何泛化父类中的一个通用函数?

问题描述

我有两个班级'A'和'B'。这两个类有一些功能和一个通用功能,即'toJson()'。

我创建了一个父类“Json”,用于将类转换为 json。

class Json
{
    public function toJSON() {
        return json_encode(get_object_vars($this));
    }
}

class A extends Json{

    private $a;
    function __construct($input = null) {
        $this->a = $input;
    }
    //getter & setter
}

class B extends Json{
    private $b;
    function __construct($input = null) {
        $this->b = $input;
    }
    //getter & setter
}


$a = new A("A")->json();
$b = new B("B")->json();

我希望这两个类都转换为 json。但是会返回“null”。

我在两个类中都添加了“toJSON()”。它按预期工作。

是否可以概括“toJSON()”?

标签: phplaravel

解决方案


如果我们跳过您的语法错误并专注于手头的问题,这一切都归结为属性可见性

您不能访问该类之外的私有属性,包括在处理继承时。您可以更改属性$a并将其更改$b为受保护或公共,以允许 JSON 类访问它们。

您可以在这里尝试使用私有:https ://3v4l.org/Vhr9M

您可以尝试在此处使用受保护:https ://3v4l.org/9neiQ


推荐阅读