fork download
  1. <?php
  2.  
  3. class MyClass {
  4. private $type = 0; // we will force this to be an int
  5. private $string = ''; // we will force this to be a string
  6. private $arr = array(); // we will force this to be an array
  7. private $percent = 0; // we will force this to be a float in the range 0..100
  8.  
  9. function __set($name, $value) {
  10. switch ($name) {
  11. case "type":
  12. $valid = is_integer($value);
  13. break;
  14. case "string":
  15. $valid = is_string($value);
  16. break;
  17. case "arr":
  18. $valid = is_array($value);
  19. break;
  20. case "percent":
  21. $valid = is_float($value) && $value >= 0 && $value <= 100;
  22. break;
  23. default:
  24. $valid = true; // allow all other attempts to set values (or make this false to deny them)
  25. }
  26.  
  27. if ($valid) {
  28. $this->{$name} = $value;
  29.  
  30. // just for demonstration
  31. echo "pass: Set \$this->$name = ";
  32. var_dump($value);
  33. } else {
  34. // throw an error, raise an exception, or otherwise respond
  35.  
  36. // just for demonstration
  37. echo "FAIL: Cannot set \$this->$name = ";
  38. var_dump($value);
  39. }
  40. }
  41. }
  42.  
  43. $myObject = new MyClass();
  44. $myObject->type = 1; // okay
  45. $myObject->type = "123"; // fail
  46. $myObject->string = 1; // fail
  47. $myObject->string = "123"; // okay
  48. $myObject->arr = 1; // fail
  49. $myObject->arr = "123"; // fail
  50. $myObject->arr = array("123"); // okay
  51. $myObject->percent = 25.6; // okay
  52. $myObject->percent = "123"; // fail
  53. $myObject->percent = array("123"); // fail
  54. $myObject->percent = 123456; // fail
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
pass: Set $this->type = int(1)
FAIL: Cannot set $this->type = string(3) "123"
FAIL: Cannot set $this->string = int(1)
pass: Set $this->string = string(3) "123"
FAIL: Cannot set $this->arr = int(1)
FAIL: Cannot set $this->arr = string(3) "123"
pass: Set $this->arr = array(1) {
  [0]=>
  string(3) "123"
}
pass: Set $this->percent = float(25.6)
FAIL: Cannot set $this->percent = string(3) "123"
FAIL: Cannot set $this->percent = array(1) {
  [0]=>
  string(3) "123"
}
FAIL: Cannot set $this->percent = int(123456)