Skip to content

Instantly share code, notes, and snippets.

@requinix
Created November 24, 2014 23:03
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 requinix/57f5fe27945ee5ae8324 to your computer and use it in GitHub Desktop.
Save requinix/57f5fe27945ee5ae8324 to your computer and use it in GitHub Desktop.
Why reverse-inheritance of namespaces would suck (part 1)
<?php
// https://bugs.php.net/bug.php?id=68485
namespace Math {
class Calculator {
public static function calculate($operator, $operand1, $operand2) {
switch ($operator) {
case "+":
return AddOperator::add($operand1, $operand2);
case "-":
return AddOperator::subtract($operand1, $operand2);
case "*":
return MultiplyOperator::multiply($operand1, $operand2);
case "/":
return MultiplyOperator::divide($operand1, $operand2);
default:
throw new \Exception("Invalid operator '{$operator}'");
}
}
}
class AddOperator {
public static function add($op1, $op2) { return $op1 + $op2; }
public static function subtract($op1, $op2) { return $op1 - $op2; }
}
class MultiplyOperator {
public static function multiply($op1, $op2) { return $op1 * $op2; }
public static function divide($op1, $op2) { return $op1 / $op2; }
}
}
namespace MoreMath {
class BetterCalculator extends \Math\Calculator {
public static function calculate($operator, $operand1, $operand2) {
switch ($operator) {
case "div":
return MoreOperators::div($operand1, $operand2);
case ">>":
return MoreOperators::rshift($operand1, $operand2);
case "<<":
return MoreOperators::lshift($operand1, $operand2);
default:
return parent::calculate($operator, $operand1, $operand2);
}
}
}
class MoreOperators {
public static function div($op1, $op2) { return floor($op1 / $op2); }
public static function rshift($op1, $op2) { return $op1 >> $op2; }
public static function lshift($op1, $op2) { return $op1 << $op2; }
}
}
namespace {
echo MoreMath\BetterCalculator::calculate("+", 1, 2); // 3
}
Copy link

ghost commented Jan 25, 2015

Lol nice one Req.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment