Skip to content

Instantly share code, notes, and snippets.

@fidelisrafael
Created June 13, 2013 16:07
Show Gist options
  • Save fidelisrafael/5774958 to your computer and use it in GitHub Desktop.
Save fidelisrafael/5774958 to your computer and use it in GitHub Desktop.
<?php
class Person {
public $name , $age , $doc_num;
protected $cpf;
public function __set($property, $value) {
return $this->setOrGetIfPropertyExists($property, $value);
}
public function __get($attr) {
return $this->setOrGetIfPropertyExists($attr , null, true);
}
public function __call($method,$value){
if(preg_match_all("/^(s|g)et([A-Z]{1}[A-z]+)$/" , $method , $matches)) {
return $this->setOrGetIfPropertyExists(array_shift($matches[2]), $value , preg_match("/^g{1}/",$method) != 0);
}
return NULL;
}
// not the best name for function ,but that's ok
private function setOrGetIfPropertyExists($property , $value , $get=false) {
if(property_exists($this, $property = strtolower($property))) {
return ($get ? $this->$property : $this->$property = is_array($value) ? array_shift($value) : $value);
}
return NULL ;
}
}
$person = new Person();
$person->setAge(22); // valid
$person->setage(20); // not valid (capital letter after 'set')
$person->setCPF('***.***.***-**'); // valid
$person->setDoc_Num('123,456,890'); // valid
$person->setdoc_Num('2123,456,890'); // invalid (the first letter must be a capital after set or get)
$person->name = 'Rafael F.';
print_r(sprintf("<pre>%s<br/>%s<br/>%s<br/></pre><br />" ,
$person->getAge() ,
$person->getCPF() ,
$person->setCPF('123.456.789-10')
));
print_r("<pre>") && print_r($person) && print_r("</pre>");
?>
@fidelisrafael
Copy link
Author

22
_..**-_*
123.456.789-10

Person Object
(
[name] => Rafael F.
[age] => 22
[doc_num] => 123,456,890
[cpf:protected] => 123.456.789-10
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment