Skip to content

Instantly share code, notes, and snippets.

@pyaesone17
Created November 26, 2017 09:57
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 pyaesone17/2046fce2e83f9a0c1e8809385a698302 to your computer and use it in GitHub Desktop.
Save pyaesone17/2046fce2e83f9a0c1e8809385a698302 to your computer and use it in GitHub Desktop.
Go lang struct composition implementation in PHP
<?php
class A {
public $dependencies = [];
public function __construct(...$arguments)
{
$this->dependencies = $arguments;
}
public function __call($name, $arguments){
foreach ($this->dependencies as $key => $dependency) {
$methods = get_class_methods($dependency);
if (in_array($name, $methods)) {
return call_user_func_array([$dependency,$name], $arguments);
}
}
}
public function __set($name, $value){
foreach ($this->dependencies as $key => $dependency) {
$vars = get_object_vars($dependency);
if (array_key_exists($name, $vars)) {
$dependency->$name = $value;
}
}
}
public function __get($name){
foreach ($this->dependencies as $key => $dependency) {
$vars = get_object_vars($dependency);
if (array_key_exists($name, $vars)) {
return $dependency->$name;
}
}
}
}
class B {
public $b;
public function hello()
{
return "Say Hello From B";
}
}
$a = new A(new B);
$a->b = "Setting from A";
echo $a->hello();
echo $a->b;
die();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment