PHP: auto set and get through magic call

This is how to set and get automatically through magic function in PHP.

class myClass
{

    public static function __call($method, $args)
    {
        /**
         * Set to only responde to set and get method calls
         */
        if (preg_match('/^(?P<action>set|get)(?P<property>.*)/', $method, $matches)) {
            $action = $matches['action'];

            $property = $matches['property'];
            $property[0] = strtolower($property[0]);

            /**
             * Set to only respond if the called property exists
             */
            if (property_exists($this, $property)) {
                switch ($action) {
                    case 'set':
                    $this->$property = $args[0];
                    break;

                    case 'get':
                    return $this->$property;
                    break;

                    default:
                    break;
                }

                return $this;
            }
        }
    }

}

Leave a Reply