Skip to content

Instantly share code, notes, and snippets.

@xemoe
Created November 4, 2015 18:03
Show Gist options
  • Save xemoe/643108bbbd9c55d7481a to your computer and use it in GitHub Desktop.
Save xemoe/643108bbbd9c55d7481a to your computer and use it in GitHub Desktop.
Traits switcher
<?php
trait Bar1
{
function getBody($type, &$body) {
switch($type) {
case 1:
$body = 'A';
break;
case 2:
$body = 'B';
break;
}
}
}
trait Bar2
{
function getBody($type, &$body) {
switch($type) {
case 3:
$body = 'C';
break;
case 4:
$body = 'D';
break;
}
}
}
class Foo
{
use Bar1, Bar2 {
Bar1::getBody insteadof Bar2;
Bar1::getBody as bar1;
Bar2::getBody as bar2;
}
function choose($type)
{
$body = '';
foreach (['bar1', 'bar2',] as $switcher) {
static::$switcher($type, $body);
}
return $body;
}
}
$foo = new Foo;
assert($foo->choose(1) == 'A');
assert($foo->choose(2) == 'B');
assert($foo->choose(3) == 'C');
assert($foo->choose(4) == 'D');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment