0

First we have a property which is the array:

    private static $_errors = array();

An error can be added by sending it to a function, which will add it to the array:

    public function addError($error){
    self::$_errors[] = $error;
}

In any function, I can easily add an error as a string like this:

if(strlen($value) < $rule_value){
                            $this->addError("More than {$rule_value} characters are needed as {$item}.");
                        }

But I want to add a key and value, for example "message" => "hello", but I don't know how to do it. This:

if(strlen($value) < $rule_value){
                            $this->addError(['min_notmet'] = "More than {$rule_value} characters are needed as {$item}.");
                        }    

does not work. I tried various things. But it has to be one and the same array, I don't want to add the errors as separate arrays inside the array. Hope you can solve this!

1 Answer 1

3

Modify your addError function:

public function addError($error, $key=false){
    if($key){
        self::$_errors[$key] = $error;
    }else{
        self::$_errors[] = $error;
    }

} 

Then it will go like this:

if(strlen($value) < $rule_value){
    $this->addError("More than {$rule_value} characters are needed as {$item}.", 'min_notmet');
}

If you don't provide $key parameter, it will just add the element as before, with numeric key.

Sign up to request clarification or add additional context in comments.

1 Comment

You could also change the parameter order and make $key optional

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.