Skip to content

Instantly share code, notes, and snippets.

@matheuseduardo
Created August 21, 2018 18:17
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 matheuseduardo/ade37bd7a9445b12c501296f89cc8269 to your computer and use it in GitHub Desktop.
Save matheuseduardo/ade37bd7a9445b12c501296f89cc8269 to your computer and use it in GitHub Desktop.
class with getters and setters predefined through magic methods
<?php
class GetrsSetrs {
public function __call($name, $arguments) {
$action = substr($name, 0, 3);
if ($action == 'get') {
return $this->get(lcfirst(substr($name, 3)));
}
else if ($action == 'set') {
$this->set(lcfirst(substr($name, 3)) , $arguments[0]);
}
}
protected function get($property) {
$this->checkPropertyExists($property);
return $this->{$property};
}
protected function set($property, $value) {
$this->checkPropertyExists($property);
$this->{$property} = $value;
}
protected function checkPropertyExists($property) {
if (!property_exists(get_class($this) , $property)) {
throw new Exception('Undefined Property');
}
}
}
<?php
require_once 'Student.class.php';
echo '<pre>';
$student = new Student();
$student->setName('Diego');
var_dump($student);
echo $student->getName();
<?php
// sample
require_once "GetrsSetrs.class.php";
class Student extends GetrsSetrs {
protected $name;
protected $email;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment