0

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?

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Weird, changing the members to public fixed it.

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

// ....

Any insight on what's going on?

3 Comments

The answer probably is in your getters...can you copy/paste them here ?
Added the getters/setters to the question
It is because of member visibility. Protected/Private members will be prefixed to designate their visibility, while public members will not.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.