Vamos a crear la clase ‘Cliente’ con las siguientes propiedades privadas:
Nombre
NIF
Pais
Importe
Vamos a crear un constructor que pida obligatoriamente el Nombre y el NIF y vamos a crear getters y setters mágicos.
Los valores no pueden estar vacíos, el NIF tiene que empezar por una letra y tener una longitud de 9 caracteres y el importe no puede ser negativo.
Probad todas las características.
class Cliente {
private $nombre;
private $nif;
private $pais;
private $importe;
function __construct($nombre, $nif) {
$this->nombre = $nombre;
$this->nif = $nif;
}
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("La propiedad $name no puede estar vacía");
}
if($name=="importe" && $value<0){
throw new Exception("El importe no puede ser negativo");
}
if($name=="nif" && $this->checkNif($value)) {
throw new Exception("NIF incorrecto");
}
$this->$name = $value;
}
private function checkNif($nif){
return (strlen($nif)!=9 || strtoupper(substr($nif, 0,1))<"A"
|| strtoupper(substr($nif, 0,1))>"Z");
}
}
$pepe=new Cliente("Pepe", "B61235712");
$pepe->nif="B12345678";
$pepe->importe=500;
echo $pepe->nombre;
var_dump($pepe);