1
<!DOCTYPE html>
<html>
<body>
<h2>Herencia y Encapsulamiento en PHP 8.3</h2>
<?php
// 1. Clase Base (Padre)
class Usuario {
public function __construct(
public string $nombre,
protected string $email,
private string $claveHash
) {}
public function getEmail(): string {
return $this->email;
}
public function getRol(): string {
return "Usuario General";
}
public function renderInfo(): string {
return "<strong>{$this->nombre}</strong> ({$this->getEmail()}) - <em>{$this->getRol()}</em>";
}
}
// 2. Clase Hija: Estudiante
class Estudiante extends Usuario {
public function __construct(
string $nombre,
string $email,
string $claveHash,
public string $cohorte = "Bootcamp 2026-A"
) {
// Llamada obligatoria al constructor padre
parent::__construct($nombre, $email, $claveHash);
}
// Sobrescritura de método (Polimorfismo)
public function getRol(): string {
return "Estudiante Activo ({$this->cohorte})";
}
}
// 3. Clase Hija: Instructor
class Instructor extends Usuario {
public function __construct(
string $nombre,
string $email,
string $claveHash,
public array $materias = []
) {
parent::__construct($nombre, $email, $claveHash);
}
public function getRol(): string {
return "Instructor Especialista en " . implode(", ", $this->materias);
}
}
// 4. Instanciación y prueba
$estudiante = new Estudiante(
"Ana Isabel Montaño",
"[email protected]",
"hash_secreto_123",
"Fullstack Cohorte 4"
);
$instructor = new Instructor(
"Prof. David Amador",
"[email protected]",
"hash_docente_999",
["PHP 8.3", "Arquitectura Web", "MySQL"]
);
echo "<p style='color:#2563eb;'>1. " . $estudiante->renderInfo() . "</p>";
echo "<p style='color:#059669;'>2. " . $instructor->renderInfo() . "</p>";
// Intentar acceder a una propiedad private desde fuera generaría un error fatal:
// echo $estudiante->claveHash; // ❌ Error: Cannot access private property
?>
</body>
</html>
Haz clic para editar este código