Skip to content

Instantly share code, notes, and snippets.

@MontealegreLuis
Created July 25, 2014 05:02
Show Gist options
  • Save MontealegreLuis/c04146272177421c3204 to your computer and use it in GitHub Desktop.
Save MontealegreLuis/c04146272177421c3204 to your computer and use it in GitHub Desktop.
More examples of Interface, Trait and Abstract Class
<?php
abstract class Animal
{
/** @type string */
protected $name;
/**
* @param string $name
*/
public function __construct($name)
{
$this->name = $name;
}
}
abstract class Vertebrate extends Animal
{
public function hasBones()
{
return true;
}
}
interface CanFly
{
public function fly();
}
interface CanEat
{
public function eat($food);
}
class Bird extends Vertebrate implements CanFly, CanEat
{
public function canFly()
{
return true;
}
public function fly()
{
return 'I use my wings';
}
public function eat($food)
{
if ($food != 'meat') {}
throw new InvalidArgumentException('Birds cannot eat meat');
}
}
class NonFlyingBird extends Bird
{
public function canFly()
{
return false;
}
}
trait Painting
{
public function paint()
{
return 'use paint';
}
}
abstract class Building{}
class House
{
use Painting;
}
abstract class Transport{}
class Plane implements CanFly
{
use Painting;
public function fly()
{
return 'I use a motor';
}
}
# $animal = new Animal(); //Won't work
$pigeon = new Bird('Pigeon');
echo var_export($pigeon->canFly(), true);
$pigeon instanceof Bird;
$pigeon instanceof Vertebrate;
$pigeon instanceof Animal;
$ostrich = new NonFlyingBird('Ostrich');
echo var_export($ostrich->canFly(), true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment