将普通PHP类序列化为关联数组
考虑一个简单的类:将普通PHP类序列化为关联数组,php,Php,考虑一个简单的类: class Token{ private $hash = ""; private $userId = ""; public function __construct($hash, $userId) { $this->hash = $hash; $this->userId = $userId; } public function getHash() { return $th
class Token{
private $hash = "";
private $userId = "";
public function __construct($hash, $userId) {
$this->hash = $hash;
$this->userId = $userId;
}
public function getHash() {
return $this->hash;
}
public function getUserId() {
return $this->userId;
}
public function setHash($hash) {
$this->hash = $hash;
}
public function setUserId($userId) {
$this->userId = $userId;
}
}
尝试将其序列化为关联数组,如下所示:
// the token
$t = new Token("sampleHash", "sampleUser");
// an array for comparison
$retObj = array();
$retObj['hash'] = $t->getHash();
$retObj['userId'] = $t->getUserId();
print_r((array) $t);
echo "<br>";
print_r($retObj);
发生什么事了?如何修复序列化,使其看起来像第二个打印行?奇怪,将成员更改为public修复了它
class Token{
public $hash = "";
public $userId = "";
// ....
有什么见解吗?PHP内部使用的名称与您为类变量指定的名称不同。通过这种方式,它可以判断一个变量(其名称确实可以很长)是
私有的
或受保护的
,而不使用除名称之外的任何其他数据(无论如何它都需要名称)。通过扩展,这将允许编译器告诉您“此变量受保护,您无法访问”
这被称为“名称混乱”,许多编译器都这样做。PHP编译器的混乱算法恰好保持了公共变量名不变。From
如果将对象转换为数组,则结果是一个数组,其元素是对象的属性。键是成员变量名,但有几个显著的例外:整数属性不可访问私有变量的类名在变量名前面;受保护变量的变量名前面有一个“*”。这些带前缀的值两边都有空字节
答案:它们必须是公共的您可以使用编写成员函数。答案可能在您的getter中…您可以将它们复制/粘贴到此处吗?将getter/setter添加到问题中这是因为成员的可见性。受保护/私有成员的前缀将指定其可见性,而公共成员则不会。
class Token{
public $hash = "";
public $userId = "";
// ....