Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

__set_state() Method

__set_state() is called when an object has been exported with var_export(), and has to be instantiated again.

__set_state() is tasked with recreating the object, assigning the previous values to it, and recreating any missing properties, such as database connections or resources.

The __set_state() method has no counterpart: var_export() does not use any magic method.

__set_state() is a static method, unlike the other magic methods. __set_state() is a magic method.

<?php

    class Elephpant {
        private $values = ['a' => 1,
                           'b' => 2,
                           ];
    
        // Checks the dictionary, or return 0
        public static function __set_state($array) {
            $object = new self();
    
            // This takes advantage of PHP object invasion
            $object->values['a'] = $array['a'] ?? '0';
            $object->values['b'] = $array['b'] ?? '0';
            
            return $object;
        }
    }

?>

Documentation

See Also