Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Slim框架无法使用受保护的变量编码为json_Php_Json_Slim - Fatal编程技术网

Php Slim框架无法使用受保护的变量编码为json

Php Slim框架无法使用受保护的变量编码为json,php,json,slim,Php,Json,Slim,基本上,我是用json编码响应的,不明白为什么它总是返回正确数量的数组成员,但它们是空的 $app->get('/api/server_list', function ($request, $response, $args) { $serverlist = new ServerListing($this->db); $servers = $serverlist->getServers(); $newResponse = $response->withJson($s

基本上,我是用json编码响应的,不明白为什么它总是返回正确数量的数组成员,但它们是空的

 $app->get('/api/server_list', function ($request, $response, $args) {
 $serverlist = new ServerListing($this->db);
 $servers = $serverlist->getServers();
 $newResponse = $response->withJson($servers);
 return $newResponse;    
 });
这是上面的输出,添加了打印服务器($servers)

以下是ServerListing的类代码:

 <?php

class ServerListing extends Listing
{
    public function getServers() {
        $sql = "SELECT * from servers";
        $stmt = $this->db->query($sql);

        $results = [];

        while($row = $stmt->fetch()) {
            $results[] = new ServerEntity($row);
        }
        return $results;
    }
}

简而言之,对象可以转换为数组

对象的公共属性将用作数组中的
$key=>$value

由于属性受保护,因此不包括这些值

虽然数组实际上是空的似乎是合乎逻辑的,但PHP将对象转换为数组的过程并没有很好的文档记录

实际上,我建议您创建一个将对象转换为数组的公共方法

class ServerEntity {
 //...
    public function toArray() {
         return array("id" => $this->id, "name" => $this->name);
    }
 //...
}
那么你可以简单地做

$app->get('/api/server_list', function ($request, $response, $args) {
    $serverlist = new ServerListing($this->db);
    $servers = $serverlist->getServers();
    $objects = array();

    foreach ($servers as $server) {
        $objects[] = $server->toArray();
    }

    $newResponse = $response->withJson($objects);
    return $newResponse;    
});
斯利姆一点魔力都没有。它依赖PHP函数进行编码
json_encode()
也不知道任何特殊技巧。如果你把一个对象传递给它进行编码,它就会得到它能从中得到的所有数据。这意味着只有它的公共属性,因为OOP就是这样工作的

但是,如果在类中实现接口,则可以控制对该类的对象进行编码时,哪些数据可用于
json\u encode()

例如:

class ServerEntity implements JsonSerializable
{
    private $id;
    private $serverName;

    // ... your existing code here

    public function jsonSerialize()
    {
        return array(
            'id'   => $this->id,
            'name' => $this->serverName,
        );
    }
}
一些测试代码:

echo(json_encode(new ServerEntity(array('id' => 7, 'name' => 'foo'))));
输出为:

{"id":7,"name":"foo"}

好吧,这是有道理的。我真的没有意识到幕后发生了什么。谢谢你的解释。
echo(json_encode(new ServerEntity(array('id' => 7, 'name' => 'foo'))));
{"id":7,"name":"foo"}