我正在構建一個包含多個輸入驗證的類,並且我決定將它們放在一個__set方法中(我不確定這是否合適,因爲我限制了它OOP經驗)。這似乎工作正常,從類外部傳遞無效值時拋出適當的錯誤。但是,如果一個變量在類中被修改,那麼_ _set方法似乎被全部忽略。PHP忽略類中的__set方法
任何瞭解將非常理解
//RESULT:::::::::::::::::::::::::::::::
// PASS: Testing : hello
// PASS: Testing exception handling
// __SET: Setting b to 123
// PASS: Testing with valid value: 123
// FAIL: Testing exception handling World2
<?php
class Test {
public $a;
private $b;
function __set($key, $val) {
switch($key) {
case 'b':
if(!is_numeric($val)) throw new Exception("Variable $b must be numeric");
break;
}
echo ("__SET: Setting {$key} to {$val}<br/>");
$this->$key = $val;
}
function __get($key) { return $this->$key; }
function bMethod() {
$this->b = "World2";
}
}
$t = new Test();
//testing a
try {
$t->a = "hello";
echo "PASS: Testing $a: {$t->a}<br/>";
} catch(Exception $e) {
echo "FAIL: Testing $a";
}
//testing b
try {
$t->b = "world";
echo "FAIL: Testing $b exception handling<br/>";
} catch(Exception $e){
echo "PASS: Testing $b exception handling<br/>";
}
//testing b with valid value
try {
$t->b = 123;
echo "PASS: Testing $b with valid value: {$t->b}<br/>";
} catch(Exception $e) {
echo "FAIL: Testing $b";
}
//bypassing exception handling with method
try {
$t->bMethod("world");
echo "FAIL: Testing $b exception handling {$t->b}<br/>";
} catch(Exception $e) {
echo "PASS: Testing $b exception handling<br/>";
}
這有我大感迷惑了至少一小時。 – Jonathan 2015-11-25 15:59:18