加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP忽略了类中的__set方法

发布时间:2020-12-13 17:51:20 所属栏目:PHP教程 来源:网络整理
导读:我正在构建一个包含许多输入验证的类,我决定将它们放在__set方法中(我不确定这是否是正确的形式,因为我有有限的OOP经验).这似乎工作正常,当从类外部传递无效值时抛出正确的错误.但是,如果在类中修改了变量,则__set方法似乎完全被忽略. 任何见解都会非常感激
我正在构建一个包含许多输入验证的类,我决定将它们放在__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( $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/>";
}
阅读__set的定义:“将数据写入不可访问的成员时运行”__ set().“无法进入是关键.在类中,所有成员都可以访问,并且__set被绕过. Overloading

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读