Yuval Adam
Yuval Adam

Reputation: 165282

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?

Upvotes: 0

Views: 120

Answers (4)

Brian Fisher
Brian Fisher

Reputation: 23989

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

Upvotes: 0

Galen
Galen

Reputation: 30170

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

Upvotes: 1

Jon
Jon

Reputation: 437554

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.

Upvotes: 1

Yuval Adam
Yuval Adam

Reputation: 165282

Weird, changing the members to public fixed it.

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

// ....

Any insight on what's going on?

Upvotes: 0

Related Questions