繁体   English   中英

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

[英]How to check if all declared variables are set?

对于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".. */        

}

最好的问候,安德烈五世。

根据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;

}

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

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

但是我认为这太过分了...

为了保持理智,请在调用fire()之前明确定义用于控制实例状态的规则,然后将其移至单独的函数。 所以你的fire()变成

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

您的验证程序只需检查所有需要就位的内容,即

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

另外,如果您的状态检查只是要确保设置了默认值,请确保在__construct构造函数中完成此操作。 这样,您就可以合理地定义要定义的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM