我正在构建一个包含许多输入验证的类,我决定将它们放在__set方法中(我不确定这是否是正确的形式,因为我有有限的OOP经验).这似乎工作正常,当从类外部传递无效值时抛出正确的错误.但是,如果在类中修改了变量,则__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( …Run Code Online (Sandbox Code Playgroud)