Search code examples
phpobjectapc

PHP __sleep() not working with APC


I have a problem with __sleep() function.

This is the code I'm using. If I remove __sleep() function from class then everything works as expected.

class Test {
    private $name;

    function setName($value){
        $this->name = $value;
    }

    function getName(){
        return $this->name;
    }

    /* Works good without this function */
    public function __sleep() {
        echo 'Sleep';
    }
}

$obj = new Test;
$obj->setName('Juris');

apc_store('test', $obj);

$objAPC = apc_fetch('test');

// Output = Juris    
echo $obj->getName();
// No output and "Call to a member function getName() on a non-object" if __sleep() function is in class. Otherwise output = Juris
echo $objAPC->getName();

Why is this code not working? Are there any limitations with using APC and __sleep()?

PHP version: 5.3.14

APC version: 3.1.10

UPDATE from answer:

This will work if I change __sleep() function to this

public function __sleep() {
    return array('name');
}

Solution

  • The magic __sleep() method must return an array of property names that should be serialized, you're returns nothing.

    Quoting from the manual (my emphasis):

    It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.