10

Problem Approch

I have a class like this with a overloaded constructors

Code

<?php 
/*
  Users Abstract Class

*/
abstract class User 
{

    protected $user_email;
    protected $user_username;
    protected $user_password;
    protected $registred_date;


    //Default constructor
    function User()
    {

    }

    //overloded constructor
    function User($input_username,$input_email,$input_password)
    {
    __set($this->user_username,$input_username);
    __set($this->user_email,$user_password);
    __set($this->user_password,$input_password);
    }

}


?>

Problem Details

Above code provides an error : error:Fatal error: Cannot redeclare User::User()

As other languages such as C++ and Java uses the above approach to overload the constructors how to do it in PHP OOP ?

Additional Information

Im using *PHP 5.3.2 in LAMP * which OOP concepts should fully supported in this version

hakre
  • 193,403
  • 52
  • 435
  • 836
Sudantha
  • 15,684
  • 43
  • 105
  • 161
  • 1
    Possible duplicate of [Best way to do multiple constructors in PHP](http://stackoverflow.com/questions/1699796/best-way-to-do-multiple-constructors-in-php) – Shadow The GPT Wizard May 17 '16 at 17:41

4 Answers4

13

PHP doesn't have overloading. It has a series of magic methods that are described as overloading in the manual (see: http://php.net/manual/en/language.oop5.overloading.php), but it's not what you're thinking of.

Also, as an aside, the correct way to write a constructor in PHP 5+ is to use the __construct method:

public function __construct(/* args */)
{
    // constructor code
}
Major Productions
  • 5,914
  • 13
  • 70
  • 149
3

You can't overload methods based on their arguments at all. in your case the answer may be as simple as my answer to a similar question here

Community
  • 1
  • 1
Kris
  • 40,604
  • 9
  • 72
  • 101
1

Overloading as you know it from other languages, is not supported in PHP. Instead, you can use func_get_args(); and work on it.

http://www.php.net/func_get_args

More information about the possibilities of overloading in PHP: http://php.net/manual/en/language.oop5.overloading.php

Dvir
  • 5,049
  • 1
  • 23
  • 32
0

You could try something like this... The use case is on the GitHub gist

<?php
use \InvalidArgumentException;
class MyClass{
    protected $myVar1;
    protected $myVar2;
    public function __construct($obj = null, $ignoreExtraValues = false){
        if($obj){
            foreach (((object)$obj) as $key => $value) {
                if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
                    $this->$key = $value;
                }else if (!$ignoreExtraValues){
                    throw new InvalidArgumentException(get_class($this).' does not have property '.$key);
                }
            }
        }
    }
}
David Culbreth
  • 2,610
  • 16
  • 26