Skip to content

Instantly share code, notes, and snippets.

@gbirke
Last active September 10, 2020 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbirke/7aa39ee5b596b702eacdd0772e8e151c to your computer and use it in GitHub Desktop.
Save gbirke/7aa39ee5b596b702eacdd0772e8e151c to your computer and use it in GitHub Desktop.
<?php
// This example shows how to override implementations without subclassing,
// using anonymous classes and traits.
interface Animal {
public function makeSound(): string;
public function move(): string;
}
trait LoudAnimal {
public function makeSound(): string {
return strtoupper( parent::makeSound() );
}
}
class Dog implements Animal {
public function makeSound(): string {
return "woof!";
}
public function move(): string {
return "Running in circles";
}
}
$loudDog = new class() extends Dog { use LoudAnimal; } ;
printf("%s\n", $loudDog->makeSound());
printf("%s\n", $loudDog->move());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment