Skip to content

Instantly share code, notes, and snippets.

@shanecp
Last active September 9, 2020 01:22
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 shanecp/8363f8706dd9b80b72a16097e51ad540 to your computer and use it in GitHub Desktop.
Save shanecp/8363f8706dd9b80b72a16097e51ad540 to your computer and use it in GitHub Desktop.
PHP Magic Methods / Attributes
On a class, add the methods Trait
```
// define the properties
/* @property $name string User's name */
class MyClass {
// add the trait
use HasAttributes;
}
```
```
<?php
trait HasAttributes
{
protected $attributes = [];
public function __set($name, $value)
{
$this->attributes[$name] = $value;
return $this;
}
public function __get($name)
{
if (!\array_key_exists($name, $this->attributes)) {
return null;
}
return $this->attributes[$name];
}
public function __isset($name)
{
return isset($this->attributes[$name]);
}
public function __unset($name)
{
unset($this->attributes[$name]);
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment