Skip to content

Instantly share code, notes, and snippets.

@blwsh
Created December 20, 2018 20:33
Show Gist options
  • Save blwsh/f2db5afe44ffbc23420824ce4e14895f to your computer and use it in GitHub Desktop.
Save blwsh/f2db5afe44ffbc23420824ce4e14895f to your computer and use it in GitHub Desktop.
PHP class that can combine multiple classes and override any of their properties and methods
<?php
/**
* Created by PhpStorm.
* User: ben
* Date: 20/12/2018
* Time: 19:07
*/
use Exception;
/**
* Class DynamicOverrideClass
*
* @package App\Classes
*/
class DynamicOverrideClass
{
/**
* @var array
*/
private $_ext = [];
/**
* @var array
*/
private $overrides = [];
/**
* @var
*/
public $_this;
/**
* DynamicOverrideClass constructor.
*
* @param array|string $extensions
* @param array|null $overrides
*/
function __construct($extensions, array $overrides = null)
{
$this->_this = $this;
if (is_array($extensions)) {
foreach ($extensions as $extension) {
$this->addExt($extension);
}
} else {
$this->addExt($extensions);
}
$this->overrides = $overrides;
}
/**
* @param $object
*/
public function addExt($object)
{
$this->_ext[] = $object;
}
/**
* @param $var
*
* @return null
*/
public function __get($var)
{
if (array_key_exists($var, $this->overrides)) return $this->overrides[$var];
foreach($this->_ext as $ext) return property_exists($ext,$var) ? $ext->$var : null;
}
/**
* @param $method
* @param $args
*
* @return mixed
* @throws \Exception
*/
public function __call($method, $args)
{
if (array_key_exists($method, $this->overrides)) return $this->overrides[$method]($this->getMainContext(), ...$args);
foreach ($this->_ext as $ext) if (method_exists($ext, $method)) return call_user_func_array([$ext, $method], $args);
throw new Exception("This Method {$method} doesn't exists");
}
/**
* ferMainClass
*/
private function getMainContext()
{
return $this->_ext[0]; // lol
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment