Skip to content

Instantly share code, notes, and snippets.

@glenjamin
Created October 29, 2012 08:43
Show Gist options
  • Save glenjamin/3972414 to your computer and use it in GitHub Desktop.
Save glenjamin/3972414 to your computer and use it in GitHub Desktop.
__callStatic used for good?
<?php
$error = new My_API_Application_Response(My_API_Application_Response::FOOLISH_HUMAN_ERROR);
return $error;
// Oh no! I've typed My_API_Application_Response twice. This feels wrong!
// How about this?
return My_API_Application_Response::FOOLISH_HUMAN_ERROR();
<?php
class My_API_Application_Response {
const SUCCESS = 1;
const FOOLISH_HUMAN_ERROR = 2;
const UNEXPECTED_ERROR = 3;
const REALISTICALLY_SHOULD_HAVE_EXPECTED_ERROR = 4;
const THERES_A_TYPO_IN_YOUR_PARAMETER_LIST = 5;
protected $code;
protected $details;
public function __construct($code, array $details = array()) {
$this->code = $code;
$this->details = $details;
}
// And here's the trick....
public static function __callStatic($constant, array $args) {
$const = 'static::' . $constant;
// Do a clean fallback when constant doesn't exist
if (!defined($const)) {
if (is_callable('parent::__callStatic')) {
return parent::__callStatic($constant, $args);
}
throw new BadMethodCallException("Undefined static method '$constant'");
}
$code = constant($const);
$details = count($args) > 1 && is_array($args[0]) ? $args[0] : array();
return new static($code, $details);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment