如何检查是否设置了所有声明的变量?

时间:2013-10-28 22:06:20

标签: php class oop validation object

我对PHP中的整个OOP范例都很陌生,但到目前为止我真的非常喜欢它。我目前正在编写一个EventSender类,它应该收集一些信息,然后将事件激活到EventHandler以及将事件写入事件日志。

当我来到“射击”部分时,让我感到震惊的是,我真的很想要一个简单的解决方案来验证我所有声明的变量都已经设置好了。有没有一种简单的方法可以这样做,甚至可能是PHP中的内置函数?

此外,下面粘贴的代码是我班级的实际代码,所以如果您有任何其他评论,请随时详细说明您的想法: - )

class Event extends Base {

private $eventKey;
private $userID;
private $value;

private function __construct($eventKey){

    $sql = Dbc::getInstance();

    //Set and escape the EVENT_KEY.
    $this->eventKey = $sql->real_escape_string($eventKey);

    $sql->select_db('my_event_db');
    $result = $sql->query('SELECT idx FROM event_types WHERE event_key = $this->$eventKey');

    //Verify that the event key given is correct and usable.
    //If failed throw exception and die.
    if($result->num_rows != 1){

        $err = 'ERROR: Illegal EVENT_KEY sent.';
        throw new Exception($err);

    }

}

public function setUserID($userID) {

    $this->userID = $userID;
    if(is_numeric($this->userID) != TRUE){

        $err = 'ERROR: Value passed as userID is not numeric.';
        throw new Exception($err);

    }

}

public function setValue($value) {

    $this->value = $value;
    //The isJson function comes from a Trait that my Base class uses.
    //The method will also throw a exception if it doesn't pass the test.
    self::isJson($this->value);

}

public function fire () {

    /* Here I want some code that swiftly checks if all declared vars have been set, which makes my method "ready to fire".. */        

}

祝你好运, AndréV。

3 个答案:

答案 0 :(得分:1)

根据Lajos Veres的回答,我设法建立了一个可以添加到Trait的类(在这种情况下我做了什么),并完成了我在初始问题中写的内容。我只是想分享它,如果有人想重复使用它: - )

protected function allPropertiesSet($self){

    /*
     * This class is dependent on the ReflectionClass.
     * This class can be called with self::allPropertiesSet(get_class());
     * The class can be called in any class who uses this trait, even if it is inherited. It's function is to validate if all your defined variables are set.
     * It will return true if all variables are set, otherwise it will return false. 
     * Some credit goes to Lajos Veres from Stackoverflow for pointing me in the right direction.
     * Author: André Valentin
     * Created: 30-10-2013
     */

    $class = new $self;
    $reflect = new ReflectionClass($class);

    $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_STATIC);
    $prop_array = array();

    foreach($props AS $prop){

        $var_name = $prop->getName();
        $class_name = $prop->class;

        if($class_name == $self){

            $prop_array[] = $var_name;

        }

    }

    foreach($prop_array AS $value){

        $var_name = $value;

        if(!isset($this->$var_name)){

            return false;

        }

    }

    return true;

}

答案 1 :(得分:0)

使用Reflection,您可以列出类的属性

http://www.php.net/manual/en/reflectionclass.getproperties.php

但我觉得这太过分了......

答案 2 :(得分:0)

为了理智,在调用fire()之前,清楚地定义管理实例状态的规则,并将其移动到单独的函数中。因此,fire()变为

function fire() {
    if ($this->validate_state()) {
        /// do whatever
        ...
    } else {
       /// report issues
    }
}

您的验证员只需检查需要就地的所有内容,即

function validate_state() {
    if ( isset($this->some_property) )
     ....
}

或者,如果您的状态检查只是想确保设置默认值,请确保在__construct构造函数中完成此操作。这样你就可以知道合理预期定义了哪些值。