PHP类:向扩展类添加其他参数

时间:2013-08-22 09:21:11

标签: php class oop

我已升级到PHP 5.4,现在我收到此错误消息,我知道为什么我收到消息但需要找出如何修复它。我知道这是因为我在扩展父类validate()方法时在子类中有其他参数。

  

严格标准:ValidateName :: validate()的声明应该是   兼容Validator :: validate($ validateThis)in   第4行的C:\ www \ testing \ ValidateName.php

我在这里看到有人说使用func_get_args(),但其他人说不使用它。

如果出现此错误,我怎么能摆脱?

我的父班     

    //Constructor
    public function validate($validateThis) {}

    // Function to add all the error messages to the array
    public function setError($msg) {
        $this->errors[] = $msg;
    }

    // Function to check if the validation passes
    public function isValid() {
        if (count($this->errors) > 0) {
            return false;
        } else {
            return true;
        }
    }

    // Function to get each of the errors
    public function fetch() {
        $error = each($this->errors);
        if ($error) {
            return $error['value'];
        } else {
            reset($this->errors);
            return false;
        }
    }
}
?>

和我的孩子上课     

    class ValidateName extends Validator {
        public function ValidateName ($name, $field) {
            //  Create an array of errors
            $this->errors = array();
            // Validate the text for that field
            $this->validate($name, $field);
        }  

        public function validate() {

            // If any of the text fields are empty add an error message to the array
            if(empty($name)) {
                $this->setError($field.' field is empty');
            }
            else {
                // Validate the text fields against the regex.  If it fails add error message to array
                if (!preg_match('/^[a-zA-Z- ]+$/', $name)) {
                    $this->setError($field.' contains invalid characters');
                }
                // if the length of the field is less than 2, add error message to array
                if (strlen($name) < 2) {
                    $this->setError($field.' is too short'); 
                }
                // if the length of the field greater than 30, add error message to array
                if (strlen($name) > 50) {
                    $this->setError($field.' is too long');
                }
            }    
        }    
    }
?>

2 个答案:

答案 0 :(得分:1)

  • // constructor评论错误,因为班级名称为Validator,请改进您的问题: - )
  • 您可以通过向子项$ignored方法添加validate()参数来“修复”它,但这可能是一个设计问题:您应该确定要验证的对象是否作为参数传递到validate方法或在施工期间(这个选择稍微改变了你的课程的性质)
  • 无论哪种方式,子类应该与父母一致,根据 LSP

答案 1 :(得分:0)

PHP 5.3.3以来的方法构造函数

__construct

所以你必须使用:

class ValidateName extends Validator {
    public function __construct($name, $field) { //It must not be ValidateName
        //  Create an array of errors
        $this->errors = array();
        // Validate the text for that field
        $this->validate($name, $field);
    } 
}

派生类的构造者可能与父母不同,但如果你写public function ClassName(),它被视为一种常用的方法,并且在派生时,你应该实现它必须接受的参数。

相关问题