Skip to content

Instantly share code, notes, and snippets.

@pjdietz
Last active December 11, 2015 15:39
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 pjdietz/4622383 to your computer and use it in GitHub Desktop.
Save pjdietz/4622383 to your computer and use it in GitHub Desktop.
Simple implementation of magic accessor methods (__get, __set, __isset, __unset) for PHP classes.
<?php
/*
* Use these methods to create automatic properties. When a property would be accessed,
* PHP will look for a function prefixed with get, set, isset, or unset followed by
* the property name with the first name capitalized. For example, the $this->name
* would be accessed as getName(), setName(), issetName(), and unsetName().
*/
/**
* @param string $propertyName
* @return mixed
*/
public function __get($propertyName)
{
$method = 'get' . ucfirst($propertyName);
if (method_exists($this, $method)) {
return $this->{$method}();
}
}
/**
* @param string $propertyName
* @param $value
*/
public function __set($propertyName, $value)
{
$method = 'set' . ucfirst($propertyName);
if (method_exists($this, $method)) {
$this->{$method}($value);
}
}
/**
* @param string $propertyName
* @return mixed
*/
public function __isset($propertyName)
{
$method = 'isset' . ucfirst($propertyName);
if (method_exists($this, $method)) {
return $this->{$method}();
}
}
/**
* @param string $propertyName
*/
public function __unset($propertyName)
{
$method = 'unset' . ucfirst($propertyName);
if (method_exists($this, $method)) {
$this->{$method}();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment