Created
September 22, 2017 16:21
-
-
Save tajulasri/4f10531909f7ec4813ce11a0bf43bd0c to your computer and use it in GitHub Desktop.
Sample of meta programming
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 | |
/** | |
* example of meta programming using php | |
*/ | |
class Argument { | |
public $attributes = []; | |
public function __construct($attributes = []) | |
{ | |
$this->attributes = $attributes; | |
$this->arrayToProperty(); | |
} | |
public static function make($attributes) | |
{ | |
return new static($attributes); | |
} | |
protected function arrayToProperty() | |
{ | |
foreach($this->attributes as $key => $value) { | |
//if property exists then we override the value | |
if(property_exists($this,$this->$key)) { | |
$this->$key = $value; | |
} | |
//create property | |
$this->$key = $value; | |
} | |
} | |
public function getAttributes() | |
{ | |
$instance = (new static()); | |
return $instance->attributes; | |
} | |
public function __call($method, $args) | |
{ | |
if(method_exists($this, $method)){ | |
return $this->$method(...$args); | |
} | |
} | |
public static function __callStatic($method,$args) | |
{ | |
return (new static)->$method(...$args); | |
} | |
public function __get($key) | |
{ | |
if(array_key_exists($key,$this->attributes)) { | |
return $this->attributes[$key]; | |
} | |
return null; | |
} | |
public function __set($key,$value) | |
{ | |
if(array_key_exists($key,$this->attributes)) { | |
$this->attributes[$key] = $value; | |
} | |
return null; | |
} | |
} | |
$model = new Argument(['name' => 'testing','rima' => 'kambing']); | |
var_dump($model->name); | |
$model->rima = 'meta programming ?'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice. foundations on methods dlm php kena tau..then br faham codes ni pasal apa.