php - 如何泛化父类中的一个通用函数?
问题描述
我有两个班级'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()”?
解决方案
如果我们跳过您的语法错误并专注于手头的问题,这一切都归结为属性可见性。
您不能访问该类之外的私有属性,包括在处理继承时。您可以更改属性$a
并将其更改$b
为受保护或公共,以允许 JSON 类访问它们。
您可以在这里尝试使用私有:https ://3v4l.org/Vhr9M
您可以尝试在此处使用受保护:https ://3v4l.org/9neiQ
推荐阅读
- c# - Blazor Server:无法在 Linux 上使用 nginx 进行部署?
- swiftui - 如何在 SwiftUI 中将模糊效果作为背景?
- javascript - 兄弟组件和父组件的数据注入失败 - vue3
- python - 使用 bs4 请求抓取
- android - 如何使用 Kotlin 在 Android Jetpack Compose 中获取上下文?
- web-component - HTML 模板与在 Web 组件中定义 HTML
- python - 使用追加方法时openpyxl第一列为空
- python - Celery max_tasks_per_child 设置未重新启动工作人员
- javascript - NodeJS Json按子数组排序
- python - 即使在启动它的 lambda 函数超时后,如何使复制命令继续在红移中运行?