<?php
class MyClass {
private $type = 0; // we will force this to be an int
private $string = ''; // we will force this to be a string
private $arr = array(); // we will force this to be an array private $percent = 0; // we will force this to be a float in the range 0..100
function __set($name, $value) {
switch ($name) {
case "type":
break;
case "string":
break;
case "arr":
break;
case "percent":
$valid = is_float($value) && $value >= 0 && $value <= 100; break;
default:
$valid = true; // allow all other attempts to set values (or make this false to deny them)
}
if ($valid) {
$this->{$name} = $value;
// just for demonstration
echo "pass: Set \$this->$name = ";
} else {
// throw an error, raise an exception, or otherwise respond
// just for demonstration
echo "FAIL: Cannot set \$this->$name = ";
}
}
}
$myObject = new MyClass();
$myObject->type = 1; // okay
$myObject->type = "123"; // fail
$myObject->string = 1; // fail
$myObject->string = "123"; // okay
$myObject->arr = 1; // fail
$myObject->arr = "123"; // fail
$myObject->arr = array("123"); // okay $myObject->percent = 25.6; // okay
$myObject->percent = "123"; // fail
$myObject->percent = array("123"); // fail $myObject->percent = 123456; // fail
PD9waHAKCmNsYXNzIE15Q2xhc3MgewogICAgcHJpdmF0ZSAkdHlwZSA9IDA7IC8vIHdlIHdpbGwgZm9yY2UgdGhpcyB0byBiZSBhbiBpbnQKICAgIHByaXZhdGUgJHN0cmluZyA9ICcnOyAvLyB3ZSB3aWxsIGZvcmNlIHRoaXMgdG8gYmUgYSBzdHJpbmcKICAgIHByaXZhdGUgJGFyciA9IGFycmF5KCk7IC8vIHdlIHdpbGwgZm9yY2UgdGhpcyB0byBiZSBhbiBhcnJheQogICAgcHJpdmF0ZSAkcGVyY2VudCA9IDA7IC8vIHdlIHdpbGwgZm9yY2UgdGhpcyB0byBiZSBhIGZsb2F0IGluIHRoZSByYW5nZSAwLi4xMDAKICAgIAogICAgZnVuY3Rpb24gX19zZXQoJG5hbWUsICR2YWx1ZSkgewogICAgICAgIHN3aXRjaCAoJG5hbWUpIHsKICAgICAgICAgICAgY2FzZSAidHlwZSI6CiAgICAgICAgICAgICAgICAkdmFsaWQgPSBpc19pbnRlZ2VyKCR2YWx1ZSk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAic3RyaW5nIjoKICAgICAgICAgICAgICAgICR2YWxpZCA9IGlzX3N0cmluZygkdmFsdWUpOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgImFyciI6CiAgICAgICAgICAgICAgICAkdmFsaWQgPSBpc19hcnJheSgkdmFsdWUpOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGNhc2UgInBlcmNlbnQiOgogICAgICAgICAgICAgICAgJHZhbGlkID0gaXNfZmxvYXQoJHZhbHVlKSAmJiAkdmFsdWUgPj0gMCAmJiAkdmFsdWUgPD0gMTAwOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgICAgIGRlZmF1bHQ6CiAgICAgICAgICAgICAgICAkdmFsaWQgPSB0cnVlOyAvLyBhbGxvdyBhbGwgb3RoZXIgYXR0ZW1wdHMgdG8gc2V0IHZhbHVlcyAob3IgbWFrZSB0aGlzIGZhbHNlIHRvIGRlbnkgdGhlbSkKICAgICAgICB9CiAgICAgICAgCiAgICAgICAgaWYgKCR2YWxpZCkgewogICAgICAgICAgICAkdGhpcy0+eyRuYW1lfSA9ICR2YWx1ZTsKCiAgICAgICAgICAgIC8vIGp1c3QgZm9yIGRlbW9uc3RyYXRpb24KICAgICAgICAgICAgZWNobyAicGFzczogU2V0IFwkdGhpcy0+JG5hbWUgPSAiOwogICAgICAgICAgICB2YXJfZHVtcCgkdmFsdWUpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIC8vIHRocm93IGFuIGVycm9yLCByYWlzZSBhbiBleGNlcHRpb24sIG9yIG90aGVyd2lzZSByZXNwb25kCgogICAgICAgICAgICAvLyBqdXN0IGZvciBkZW1vbnN0cmF0aW9uCiAgICAgICAgICAgIGVjaG8gIkZBSUw6IENhbm5vdCBzZXQgXCR0aGlzLT4kbmFtZSA9ICI7CiAgICAgICAgICAgIHZhcl9kdW1wKCR2YWx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