Skip to content

Instantly share code, notes, and snippets.

@i-am-tom
Last active October 1, 2016 22:33
Show Gist options
  • Save i-am-tom/cb037039272f1738332b to your computer and use it in GitHub Desktop.
Save i-am-tom/cb037039272f1738332b to your computer and use it in GitHub Desktop.
Simple example of prototype OOP in PHP.
<?php
// Create and spec a new prototype for animals.
$animal = new Object;
$animal->is_animal = true;
// Create and spec a new prototype for dogs.
$dog = new Object($animal);
$dog->bark = function () {
echo 'Woof!', PHP_EOL;
};
// Create our useful object.
$lucky = new Object($dog);
$lucky->name = 'Lucky';
echo $lucky->name, PHP_EOL; // Lucky
$lucky->bark(); // Woof!
if ($lucky->is_animal) // true
echo 'Hooray!';
<?php
/**
* The prototype class.
*/
class Object
{
/**
* The object's data.
*/
private $__hash = [];
/**
* The object's prototype.
*/
private $prototype = null;
/**
* Make a blank prototype by default.
*/
public function __construct($prototype = null)
{
$this->prototype = $prototype ?? new stdClass;
}
/**
* Get a property.
* @param string $name
*/
public function __get(string $key)
{
return $this->__hash[$key] ?? $this->prototype->$key ?? null;
}
/**
* Add a new variable, function or otherwise.
* @param string $name The variable's name.
* @param callable $function
*/
public function __set(string $name, $value)
{
$this->__hash[$name] = $value;
}
/**
* Call a method in the prototype.
* @param string $function
* @param array $params
* @return mixed
*/
public function __call($function, array $params)
{
if (!is_callable($this->$function))
throw new \InvalidArgumentException;
return $this->$function->call($this, ...$params);
}
/**
* Resets this object's prototype.
* @param Object $that
* @return Object $this
*/
public function extend(Object $that)
{
$this->prototype = $that;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment