php - PHP,使用类访问JSON中的数据
问题描述
我需要使用类来访问 JSON 数据库中的数据。我的代码有一些错误,但我不知道它们在哪里。任何人都可以展示我需要更改哪些内容才能使其正常工作?谢谢。
<?php
class Character {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName($name){
return $this->name;
}
}
$data = file_get_contents("databas.json");
$data = json_decode($data, true);
foreach($data['results'] as $e) {
$character = new Character($e['name']);
$characters[] = $character;
}
foreach($characters as $character) {
echo "Name: " . $character->getName();
}
?>
解决方案
你的方法有一个额外的参数
public function getName($name){
return $this->name;
}
当你这样调用它时会发出错误
$character->getName()
没有必需的参数:在这种情况下,只需从方法定义中删除它。我想你复制了它并重命名了它然后忘记删除参数等等......别担心我已经这样做了十亿次......
public function getName(){
return $this->name;
}
您在沙盒中的代码
输出:
<br />
<b>Warning</b>: Missing argument 1 for Character::getName(), called in [...][...] on line 26 and defined in <b>[...][...]</b> on line <b>10</b><br />
Name: foo
干杯!
推荐阅读
- python - django 模型是否支持多个 slug?
- android-studio - 我的一个项目的模拟器上有多个应用程序
- android - Firebase MLKit QRCode 扫描失败,没有错误堆栈跟踪
- ios - Flutter 应用程序在 ios 模拟器中运行时总是崩溃
- python - 使用 bs4 的 Python webscrape 跳过了第一项,但其余的都很好
- google-apps-script - Google Sheets onEdit - 尝试通过更改同一行中列的值将一行复制到新工作表
- python - 如何更好地定位颜色条?
- scala - 为什么对模板类的两个成员进行 + 操作会导致类型不匹配错误?
- python - 如何将 3D 和 2D 数组放入 pandas DataFrame
- javascript - 将带有阻塞 for 循环的同步 js 函数转换为 websocket 更新到 html 表到异步 - JS/JQuery