开发者

Serializing a plain PHP class to an associative array

Consider a simple class:

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;
    }
}

Trying to serialize it to an associative array, like so:

// 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);

I get this:

Array ( [�Token�hash] => sampleHash [�Token�userId] => sampleUser )
Array ( [hash] => sampleHash [userId] => sampleUser )

What's going on? How do I fix the serialization to look like the second print line?


From http://www.php.net/manual/en/language.types.array.php#language.types.array.casting

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side....

Answer: they must be public


PHP is internally using different names than the ones you specify for your class variables. This way it can tell that a variable (whose name can be quite long indeed) is private or protected without using any additional data apart from its name (which it was going to need anyway). By extension, this is what will allow the compiler to tell you "this variable is protected, you can't access it".

This is called "name mangling", and lots of compilers do it. The PHP compiler's mangling algorithm just happens to leave public variable names untouched.


Weird, changing the members to public fixed it.

class Token{
    public $hash = "";
    public $userId = "";

// ....

Any insight on what's going on?


You could write a member function using PHP's ReflectionClass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜