首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP忽略类内的__set方法

问PHP忽略类内的__set方法
EN

Stack Overflow用户
提问于 2009-04-28 18:46:56
回答 2查看 2K关注 0票数 7

我正在构建一个带有许多输入验证的类,并决定将它们放在一个__set方法中(我不确定这是否是正确的形式,因为我的OOP经验有限)。这似乎工作得很好,当从类外部传递无效值时抛出适当的错误。但是,如果在类中修改了变量,_ _set方法似乎全部被忽略了。

任何洞察力都将不胜感激。

代码语言:javascript
复制
//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/>";
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-04-28 18:49:45

阅读__set的定义:"__set()是在向无法访问的成员写入数据时运行的。“无法访问是这里的关键。在类中,所有成员都是可访问的,并且绕过了__set。Overloading

票数 11
EN

Stack Overflow用户

发布于 2009-04-28 18:57:38

php documentation的文档中写道:

__get()用于从无法访问的成员读取数据。

所以,你可以这样做:

代码语言:javascript
复制
<?php
class Test {
    private $_params = array();

    function __set( $key, $val ) {
        ...
        $this->_params[$key] = $val;
    }

    function __get( $key ) {
        if (isset($this->_params[$key])) return $this->$key;
        throw Exception("Variable not set");
    }

    ...
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/799332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档