Search code examples
phpclassinheritanceextend

Extending PHP class and ignoring certain methods


//What I want in contact_form classis use couple of method from registration class to validate contact form. However I want to exclude the last method(validate_username), and show different error message, for example, in validate_message, instead of showing "invalid message". I want to show "Please make sure your message is atleast 50 characters long". Basically I do not want to make a different class that validate contact_form specially because I will be using same method that I used in registration form.

Thankyou.

class registration{
    function __construct($data){
        //sanitize data
    }

    function validate_empty(){
        //validate empty fields
        //error: do not leave anything empty
    }

    function validate_email(){
        //validate email
        //error: invalid email
    }

    function validate_name(){
        //validate name
        //error: invalid name
    }

    function validate_message(){
        //validate message
        //error: invalid message
    }

    function validate_username(){
        //validate username
        //error: invalid username
    }
}

class contact_form extends registration{

}

Solution

  • You can simply redefine the validate_username() method in the contact_form class:

        class contact_form extends registration{
            function validate_username(){
                //Add the new error message here to override the older one
            }
        }