June 14, 2011

Should this function be public or private?

Question by Roman

I am verifying the email in database in form validation in CodeIgniter by using callback in rule. For example

$this -> form_validation -> set_rules( 'email', 'Email address', 'trim|valid_email|callback_email_exists' );

The email_exists function is:

public function email_exists($email)
    {
        $this -> load -> model('account_model');
        $exists = $this -> account_model -> email_registered( $email );
        if ( $exists == true )
        {
            $this -> form_validation -> set_message ( 'email_exists', 'Email already exists.');
            return false;
        }
        return true;        
    }

It works fine. However, shouldn’t the above email_exists function be a private function instead of public?
I try to make it private like private function _email_exists($email) and i call back it by callback__email_exists

However I get the error:

Fatal error: Call to private method Account::_email_exists() from context 'CI_Form_validation' in ....(line number)

Can someone tell me what’s wrong?

Answer by Itay Moav

If you need to call it from outside the object (whether as callback or directly) it should be public

Answer by Starx

You are validating the email, on the basis of your model account_model, so this makes the function more centered to the private boundary. You will not achieve anything significant, by making this function public, instead you can make this function what it is

A PRIVATE FUNCTION TO CHECK EMAILS FOR MODEL account_model

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!