magic method call


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. class Person {
  3. private $firstName;
  4. private $lastName;
  5. private $age;
  6. private $country;
  7. function __call($method, $arguments) {
  8. $prefix = strtolower(substr($method, 0, 3));
  9. $property = strtolower(substr($method, 3));
  10. if (empty($prefix) || empty($property)) {
  11. return;
  12. }
  13. if ($prefix == "get" && isset($this->$property)) {
  14. return $this->$property;
  15. }
  16. if ($prefix == "set") {
  17. $this->$property = $arguments[0];
  18. }
  19. }
  20. }
  21. $personObj = new Person;
  22. $personObj->setFirstName("Pepe");
  23. $personObj->setLastName("Argento");
  24. $personObj->setAge(50);
  25. $personObj->setCountry("Argentina");
  26. echo "Nombre: ".$personObj->getFirstName()." ".$personObj->getLastName()."\n";
  27. echo "Edad: ".$personObj->getAge()."\n";
  28. echo "País: ".$personObj->getCountry()."\n";
  29. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.