Last active
December 29, 2018 01:54
-
-
Save ivansammartino/e2172f412a8b147b0e9f7dcffd32f470 to your computer and use it in GitHub Desktop.
PHP interface example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// interfaccia | |
interface Colore { | |
function color(); // definisce il colore del testo | |
function bg_color(); // definisce il colore di sfondo | |
} | |
// colori | |
class Giallo implements Colore { | |
public function color() { | |
return '#000'; // testo nero | |
} | |
public function bg_color() { | |
return '#fc0'; // sfondo giallo | |
} | |
} | |
class Rosso implements Colore { | |
public function color() { | |
return '#fff'; // testo bianco | |
} | |
public function bg_color() { | |
return '#c00'; // sfondo rosso | |
} | |
} | |
class Verde implements Colore { | |
public function color() { | |
return '#fff'; // testo bianco | |
} | |
public function bg_color() { | |
return '#0c0'; // sfondo verde | |
} | |
} | |
// le mie classi | |
class Tizio { | |
protected $colore; | |
public function __construct(Colore $colore) { // nota che passo l'interfaccia Colore, non il singolo colore (Giallo, Rosso) | |
$this->colore = $colore; | |
} | |
public function get_color(){ | |
return $this->colore->color(); | |
} | |
public function get_bg_color(){ | |
return $this->colore->bg_color(); | |
} | |
} | |
class Caio { | |
protected $colore; | |
public function __construct(Colore $colore) { // idem come sopra | |
$this->colore = $colore; | |
} | |
public function get_color(){ | |
return $this->colore->color(); | |
} | |
public function get_bg_color(){ | |
return $this->colore->bg_color(); | |
} | |
} | |
// vediamo che succede... | |
$colore = new Giallo(); // cambia con Rosso o Verde: lo fai solo qui una volta per tutte | |
// creo Tizio | |
$tizio = new Tizio($colore); | |
echo '<p style="color:' . $tizio->get_color() . ';background:' . $tizio->get_bg_color() . '">Sono Tizio!<p>'; | |
// creo Caio | |
$caio = new Caio($colore); | |
echo '<p style="color:' . $caio->get_color() . ';background:' . $caio->get_bg_color() . '">Sono Caio!<p>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment