首页 > 解决方案 > 使用 php OOP 检查空输入验证的类

问题描述

我不明白为什么这不起作用以及对 oop im 初学者关于 oop 范式的任何建议

我的课

class formvalidation  {

     public function check_empty_input($inputs=[]){
         $checked = false;

         foreach($inputs as $valor){
             if(empty($valor)){
                 $checked = false;
                 break;  
             } else {
                 $checked = true;
             }
         }

         if($checked = true){return true;}
         else {return false;}
     }

}

检查帖子是否为空

  $formvalidation= new formvalidation();

  $inputs = array($_POST['name'],$_POST['email'],$_POST['pass'],$_POST['confirmpass']);
  if($formvalidation->check_empty_input($inputs)) 

标签: phpoop

解决方案


好吧,问题出在返回中,如果您使用=的是比较运算符,而不是您应该使用的地方==,因此该函数将始终返回 true ......您也应该从不使用的那一刻起使用静态函数需要一个对象来调用这个函数,试试这个:

<?php

class formvalidation {
    public static function check_empty_input($inputs = []) : bool {
        $everything_filled = true; //start with this supposition
        foreach ($inputs as $valor) {
            if (empty($valor)) {
                $everything_filled = false; // is something is empty, than the supposition is false
                break;
            }
        }
        return $everything_filled; // return the supposition result value
    }
}

$is_my_inputs_filled = formvalidation::check_empty_inputs([
    $_POST['name'],
    $_POST['email'],
    $_POST['pass'],
    $_POST['confirmpass'],
]);

如果它不起作用,请更好地解释“不起作用”的含义


推荐阅读