Last active
September 9, 2020 01:22
-
-
Save shanecp/8363f8706dd9b80b72a16097e51ad540 to your computer and use it in GitHub Desktop.
PHP Magic Methods / Attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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