Tipos de intersección en PHP

Nivel 5502 pulsaciones

Usa tipos de intersección para requerir múltiples interfaces.

Código PHP

// Primera interfaz
1interface Printable {
2 public function print(): string;
3}
4
// Segunda interfaz
5interface JsonExportable {
6 public function serialize(): string;
7}
8
// Una clase puede implementar varias interfaces
9class Document implements Printable, JsonExportable {
// Propiedad privada $content promovida en el constructor
10 public function __construct(private string $content) {}
11
// Exigido por Printable
12 public function print(): string {
13 return $this->content;
14 }
15
// Exigido por JsonExportable: devuelve JSON
16 public function serialize(): string {
17 return json_encode(["content" => $this->content]);
18 }
19}
20
// Tipo intersección (PHP 8.1+): el argumento debe implementar ambas interfaces
21function process(Printable&JsonExportable $item): void {
22 echo $item->print();
23}
24
// Document cumple ambas, así que imprime Hello
25process(new Document("Hello"));

Salida

Hello
Practicar escribiendo este código

Practica escribiendo este código. Los resultados no se registran en el ranking.

Símbolos de este código

Los símbolos que escribes en este código PHP y cuántas veces aparecen.

  • (× 10
  • )× 10
  • {× 7
  • }× 7
  • ;× 6
  • :× 5
  • $× 5
  • "× 4
  • >× 4
  • _× 3

Más ejemplos de PHP de nivel 5

← Práctica de mecanografía de PHP