Getters/Setters mágicos

class Libro {

    private $titulo;
    private $autor;
    private $paginas;

    function __construct($titulo) {
        $this->titulo = $titulo;
    }

    function __get($name) {
        if (!property_exists($this, $name)) {
            throw new Exception("La propiedad $name no existe");
        }
        return $this->$name;
    }

    function __set($name, $value) {
        if (!property_exists($this, $name)) {
            throw new Exception("La propiedad $name no existe");
        }
        if (empty($value)) {
            throw new Exception("El valor $name no puede estar vacío");
        }
        if ($name == "paginas" && ($value < 10 || $value > 1000)) {
            throw new Exception("Páginas entre 10 y 1000");
        }
        $this->$name = $value;
    }

}

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos