我对 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".. */
}
最好的问候,安德烈 V。