Combinación setters/getters mágicos y estilo Java

class Libro {

    private $titulo;
    private $autor;
    private $paginas;
    function getTitulo() {
        return $this->titulo;
    }

    function getAutor() {
        return $this->autor;
    }

    function getPaginas() {
        return $this->paginas;
    }

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

    function setAutor($autor) {
        $this->autor = $autor;
    }

    function setPaginas($paginas) {
        $this->paginas = $paginas;
    }

        function __construct($titulo) {
        $this->__set("titulo",$titulo);
    }

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

    function __set($name, $value) {
        $metodo="set$name";
        if (!method_exists($this, $metodo)) {
            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->$metodo($value);
    }

}

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos