. . .

Constructor Overloading in PHP

Published: May 12, 2011

On This Page

    There is no simple method of overloading constructors in PHP. There are few workarounds to achieve this. I use the following technique.

    class UserIdentity extends CUserIdentity
    {
    	public function __construct()
    	{
    		$arg_list = func_get_args();
    		switch(func_num_args())
    		{
    			case 1:
    				// calling from admin end....
    				$this->_user = $arg_list[0];;
    				parent::__construct($this->_user->username,$this->_user->password);
    			break;
    			case 2:
    				// calling from Login Model....
    				parent::__construct($arg_list[0],$arg_list[1]);
    			break;
    		}
    	}
    	// ........
    }

     Usage:

     

    // passing two parameters to instantiate the class
    $identity=new UserIdentity($this->username,$this->password);
    $identity->authenticate();
    // passing one parameter to instantiate the same class
    $user = Users::model()->notsafe()->findByPk($id);
    if(!empty($user)){
    	$identity2 = new UserIdentity($user);
    	$identity2->loginMember();
    }

     

    Don't forget to share this post

      Let's Build Digital Excellence Together


      • Cost Efficient Solutions.
      • Minimal Timelines.
      • Effective Communication.
      • High Quality Standards.
      • Lifetime Support.
      • Transparent Execution.
      • 24/7 Availability.
      • Scalable Teams.

      Join Our 200+ Happy Clients Across Globe


      Free Consultation.

        Do you need tech help of your startup/business? Experts from our team will get in touch with you.

        Please do not post jobs/internships inquiries here.