Skip to content

Instantly share code, notes, and snippets.

@johnkary
Last active February 14, 2019 20:06
Show Gist options
  • Save johnkary/d8ec6e849267f1fd2b2071402cb91c4d to your computer and use it in GitHub Desktop.
Save johnkary/d8ec6e849267f1fd2b2071402cb91c4d to your computer and use it in GitHub Desktop.
Example of meta-programming in PHP 5.6+ using Ruby's method_missing concept. See in action here: https://3v4l.org/pfWTh
<?php
class Sample
{
private $name;
// Name is required!
public function __construct($name) {
$this->setName($name);
}
public function setName($name) {
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
class ModuleSample
{
/**
* @var Sample
*/
private $originalSample;
public function __construct(Sample $originalSample)
{
$this->originalSample = $originalSample;
}
public function __call($methodName, $arguments)
{
return $this->originalSample->$methodName(...$arguments);
}
}
$sample = new Sample("John");
$moduleSample = new ModuleSample($sample);
$moduleSample->setName("Andrew"); // Class ModuleSample does not define a method named setName()!
echo $moduleSample->getName(); // ModuleSample forwards the method call and arguments to Sample and returns the result
// ^^^ Prints "Andrew"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment