Created
April 29, 2012 21:27
-
-
Save madfriend/2553346 to your computer and use it in GitHub Desktop.
PHP 5.4 Pattern Traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace traits; | |
trait Singleton { | |
// Для тех, кто не предусмотрел конструктор в классе | |
private function __construct() { | |
} | |
public static function getInstance() { | |
static $_instance = NULL; | |
$class = __CLASS__; | |
return $_instance ?: $_instance = new $class; | |
} | |
public function __clone() { | |
trigger_error('Cloning '.__CLASS__.' is not allowed.', E_USER_ERROR); | |
} | |
} | |
trait Prototype { | |
private | |
$_props = array(), | |
$_methods = array(); | |
function &__get($name) { | |
if (array_key_exists($name, $this->_props )) { | |
return $this->_props[$name]; | |
} | |
elseif (array_key_exists($name, $this->_methods )) { | |
return $this->_methods[$name]; | |
} | |
return null; | |
} | |
function __set($name, $value) { | |
if (is_object($value) && is_callable($value)) { | |
if (!array_key_exists($name, $this->_methods)) { | |
$this->_methods[$name] = array(); | |
} | |
if($value instanceof \Closure) { | |
$value = $value->bindTo($this); | |
} | |
$this->_methods[$name][] = $value; | |
} | |
else { | |
$this->_props[$name] = $value; | |
} | |
} | |
function __call($name, $args = array()) { | |
if (array_key_exists($name, $this->_methods)) { | |
$methods = $this->_methods[$name]; | |
if (is_array($methods)) { | |
foreach($methods as $method) { | |
if(!is_null($result = call_user_func_array($method, $args))) { | |
return $result; | |
} | |
} | |
} | |
} | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: