Created
August 21, 2018 18:17
-
-
Save matheuseduardo/ade37bd7a9445b12c501296f89cc8269 to your computer and use it in GitHub Desktop.
class with getters and setters predefined through magic methods
This file contains 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
<?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'); | |
} | |
} | |
} | |
This file contains 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
<?php | |
require_once 'Student.class.php'; | |
echo '<pre>'; | |
$student = new Student(); | |
$student->setName('Diego'); | |
var_dump($student); | |
echo $student->getName(); |
This file contains 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
<?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