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); } }
Mes: junio 2019
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; } }
Clase Empleado
class Empleado { private string pNombre; private string pDni; private decimal pSueldo; public string Nombre { get { return pNombre; } set { Console.WriteLine("Set de nombre"); if (value.Length < 3) { throw new Exception("El nombre debe tener una longitud mayor de 3"); } else { this.pNombre = value; } } } public string Dni { get { return this.pDni; } set { this.pDni = value; } } public decimal Sueldo { get { return this.pSueldo; } set { this.pSueldo = value; } } public Empleado(string nombre) { Console.WriteLine("Constructor 1"); this.Nombre = nombre; } public Empleado(string nombre, string dni) : this(nombre) { Console.WriteLine("Constructor 2"); this.Dni = dni; } public Empleado(string nombre, string dni, decimal sueldo) : this(nombre, dni) { Console.WriteLine("Constructor 3"); this.Sueldo = sueldo; } }