首页 > 解决方案 > 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();
            } 


 ?>

标签: phpjsonclassoop

解决方案


你的方法有一个额外的参数

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

干杯!


推荐阅读