__set() Method

__set() is a magic method: it is called when a property cannot be accessed, either because it doesn’t exist, or because its visibility prevents it. It is used to give a value to the property.

That way, it is possible to create dynamically properties, without hardcoding them.

The __set() method is usually paired with the __get() method.

<?php

class X {
    private $values = ['a' => 1,
                       'b' => 2,
                       ];

    // Checks the dictionary, or return 0
    function __set($name, $value) {
        if (isset($this->values[$name])) {
            $this->values[$name] = $value;
        }

        //do not set new values
    }
}

?>

Documentation

See also PHP’s magic methods: Invoke, toString, get, set – Class wizardry in a nutshell.

Related : Magic Methods, __get() Method, __isset() Method, Magic Constants, __unset() Method, Magic Methods, Magic Property, Property Hook