Patrones de diseño - Creacionales | 1.7 - Singleton en java
Ricardo García Jiménez@ricardogj08
1<?php 2 3class MySingleton { 4 private static $instance; 5 private string $x; 6 7 private function __construct(string $x) 8 { 9 $this->x = $x; 10 } 11 12 /** 13 * Los métodos estáticos los hacen accesibles 14 * sin la necesidad de instanciar una clase. 15 * 16 * No se puede utilizar $this con métodos estáticos, 17 * en su lugar se utiliza self 18 */ 19 public static function getInstance(string $x = ''): self 20 { 21 if (empty(self::$instance)) { 22 /** 23 * Equivalente a: 24 * self::$instance = new MySingleton($x); 25 */ 26 self::$instance = new self($x); 27 } 28 29 return self::$instance; 30 } 31 32 public function getX(): string 33 { 34 return $this->x; 35 } 36 37 public function setX(string $x): void 38 { 39 $this->x = $x; 40 } 41} 42 43// $a = new MySingleton('Hola'); // Error 44$a = MySingleton::getInstance('Hola Mundo'); 45 46echo $a->getX().PHP_EOL; // Hola Mundo 47 48$b = MySingleton::getInstance('Otra instancia'); 49 50echo $b->getX().PHP_EOL; // Hola Mundo 51 52$b->setX('Instancia compartida'); 53 54echo $b->getX().PHP_EOL; // Instancia compartida 55echo $a->getX().PHP_EOL; // Instancia compartida
Escribe una respuesta