Skip to content

Instantly share code, notes, and snippets.

@ivansammartino
Last active December 29, 2018 01:59
Show Gist options
  • Save ivansammartino/6af61198edb7ad2c56d80276f530e39f to your computer and use it in GitHub Desktop.
Save ivansammartino/6af61198edb7ad2c56d80276f530e39f to your computer and use it in GitHub Desktop.
PHP interface example (english)
<?php
// interface
interface Color {
function color(); // define text color
function bg_color(); // define background color
}
// colors
class Yellow implements Color {
public function color() {
return '#000'; // black text
}
public function bg_color() {
return '#fc0'; // yellow background
}
}
class Red implements Color {
public function color() {
return '#fff'; // white text
}
public function bg_color() {
return '#c00'; // red background
}
}
class Green implements Color {
public function color() {
return '#fff'; // white text
}
public function bg_color() {
return '#0c0'; // green background
}
}
// my classes
class Foo {
protected $color;
public function __construct(Color $color) { // notice that I pass the Color interface, not the real color class (Yellow, Red, Green)
$this->color = $color;
}
public function get_color(){
return $this->color->color();
}
public function get_bg_color(){
return $this->color->bg_color();
}
}
class Bar {
protected $color;
public function __construct(Color $color) { // same as before
$this->color = $color;
}
public function get_color(){
return $this->color->color();
}
public function get_bg_color(){
return $this->color->bg_color();
}
}
// let's see what happens...
$color = new Yellow(); // if you change your mind and want the Red or Green background in your classes, you do it once-for-all here!
// create Foo
$foo = new Foo($color);
echo '<p style="color:' . $foo->get_color() . ';background:' . $foo->get_bg_color() . '">I am Foo!<p>';
// create Bar
$bar = new Bar($color);
echo '<p style="color:' . $bar->get_color() . ';background:' . $bar->get_bg_color() . '">I am Bar!<p>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment