【发布时间】:2023-03-13 04:07:02
【问题描述】:
我有一个对象。我需要将其转换为 JSON 进行存储,但是当我尝试将其编码为 JSON 时,它会返回一个空的 JSON 对象。当我尝试使用json_last_error.
我使用的代码
echo $payload["sub"];
echo json_encode($user);
echo json_last_error_msg();
我得到的结果
"102573480781696194937{}No error".
我正在尝试编码的用户类
<?php
/**
* Created by PhpStorm.
* User: Student
* Date: 13-4-2018
* Time: 10:40
*/
namespace php;
class User
{
private $isAdmin = false;
private $registeredFood = array();
private $googleID;
private $name;
private $notes = array();
private $email;
/**
* User constructor.
* @param $googleID
*/
public function __construct($googleID)
{
$this->googleID = $googleID;
}
/**
* @return mixed
*/
public function getGoogleID()
{
return $this->googleID;
}
/**
* @return bool
*/
public function isAdmin()
{
return $this->isAdmin;
}
/**
* @param bool $isAdmin
*/
public function setIsAdmin($isAdmin)
{
$this->isAdmin = $isAdmin;
}
/**
* @return array
*/
public function getRegisteredFood()
{
return $this->registeredFood;
}
/**
* @param array $registeredFood
*/
public function setRegisteredFood($registeredFood)
{
$this->registeredFood = $registeredFood;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return array
*/
public function getNotes()
{
return $this->notes;
}
/**
* @param array $notes
*/
public function setNotes($notes)
{
$this->notes = $notes;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
*/
public function setEmail($email)
{
$this->email = $email;
}
}
?>
希望有人能帮帮我
【问题讨论】:
-
JSON 用于编码数据,不适用于类或代码位。我不确定你在变量
$user中有什么内容。 -
你希望它编码什么?所有属性都是私有的。
-
@cars10m 我在其中存储了一个用户对象
-
如果您想完全控制编码的 json 对象,我建议您查看 PHP 的 JsonSerializable 接口。