php类有两个参数不同的方法,如何利用构造函数?

g6ll5ycj  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(241)

我想创建一个类,比如说它叫做验证,它有两个函数 registrationValloginVal .
我想传递来自两个不同页面的数据,这两个页面将使用同一个类。我想初始化构造函数中的变量,使它看起来更干净。。。我该怎么做?
如果没有所有的变量都要传递给构造函数,如何从一个页面调用构造函数?
例如:
注册页

$obj = new validation($password, $password2, $email, $phone);
$obj->registrationVal();

登录页面

$obj = new validation($email, $password);
$obj->loginVal();
pgky5nke

pgky5nke1#

你可以做这样的东西。这不是最好的代码,但对于初学者来说也不错。

<?php

class Validator
{
    private array $params;
    private array $validated = [];
    private array $errors = [];

    public function __construct(array $params)
    {
        $this->params = $params;
        $this->validate();
    }

    private function validate(): void
    {
        foreach ($this->params as $field => $param){
            $validationMethod = 'validate' . ucfirst(strtolower($field));
            if(! method_exists($this, $validationMethod)){
                continue;
            }
            if($error = $this->{$validationMethod}($param)){
                $this->errors[$field] = $error;
            }else{
                $this->validated[$field] = $param;
            }
        }
    }

    public function validateOrFail(): void
    {
        if($this->hasErrors()){
            throw new ValidationException($this->getErrors());
        }
    }

    public function validated(): array
    {
        return $this->validated;
    }

    private function validateLogin($value): ?string
    {
       //validation logic - return null on success or error string
        return $validation_result;
    }

    public function __get($name)
    {
        return $this->params[$name] ?? null;
    }

    public function getErrors(): array
    {
        return $this->errors;
    }

    public function hasErrors(): bool
    {
        return count($this->errors) > 0;
    }
}

必须为登录字段编写validatelogin()或密码字段编写validatepassword()等验证方法。
工作原理:

$params = [
  'login' => 'login',
  'password' => 'password'
  ...
];
$validator = new Validator($params);
//it will throw exception when validation failing.
$validator->validateOrFail();
//or you can manually working with errors
if($validator->hasErrors()){
  ...
}
$password = $validator->password;

//or you can get only validated fields
$params = $validator->validated();

相关问题