Skip to content

Instantly share code, notes, and snippets.

@tajulasri
Created September 22, 2017 16:21
Show Gist options
  • Save tajulasri/4f10531909f7ec4813ce11a0bf43bd0c to your computer and use it in GitHub Desktop.
Save tajulasri/4f10531909f7ec4813ce11a0bf43bd0c to your computer and use it in GitHub Desktop.
Sample of meta programming
<?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 ?';
@nasrulhazim
Copy link

nice. foundations on methods dlm php kena tau..then br faham codes ni pasal apa.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment