1

This is Employee.class.php

class Employee

{

    public $first_name;
    public $last_name;
    public $date_of_birth;



public function __construct($fn, $ln, $dob)

{
    $this->first_name = $fn;
    $this->last_name = $ln;
    $this->date_of_birth = $dob;

}

public function registerEmployee() 

{
    require '../config.php';
    $stmt = $dbh->prepare("INSERT INTO emp_reg(e_name,
                                             e_lname,
                                             e_dob) VALUES(?,?,?)");
    $stmt->execute(array($this->first_name,
                         $this->last_name, 
                         $this->date_of_birth));

    echo "Saved Successfully";
}

public function return_employee_data($employee_id)

{
    require '../config.php';
    $stmt = $dbh->query("SELECT * FROM emp_reg WHERE e_id = '$employee_id'");
    $arr = $stmt->fetchall(PDO::FETCH_ASSOC);
    $res = json_encode($arr);
    echo $res;
}



}

When I'm going to require this class in some other file say xyz.php just to

return_employee_data($employee_id);

I've to create an object in that file like

// constructor overloading is not possible so I can't create `$EmployeeObject` like this.
$EmployeeObject = new Employee();

so I can't run this function return_employee_data($employee_name); like this

$EmployeeObject->return_employee_data($employee_name); //not possible in this new file

If constructor overloading is not possible then how can I create objects with given parameters, and without any parameter? I'd also like to create objects with variable parameters in other files where we have included class definitions only, and the file data either provides no data or variable data to create an object of such definition as above?

If we cannot create an object how can I call its underlying functions for solving any specific problem?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • It's pretty confusing what you're asking. But basically: either your object ***requires*** certain constructor parameters or it doesn't. If you want to be able to create object instances with may not have certain data, then you need to make those optional in the constructor. However, I have the feeling you're mixing too much responsibility into one class to begin with. – deceze Dec 24 '14 at 12:40
  • You can either try a factory object or capturing a variable number of parameters with func_get_args. Factory being your best bet, I think... If you need every method to be called the same, use func_get_args or give it a second thought. Can you verbalize what each constructor is doing?. That could be the name of the method. – The Marlboro Man Dec 24 '14 at 12:40
  • @deceze Only i have to load data in database table and fetch it from the table for that is the class meant and for data fetching in one file it provides name/Id as one parameter and for loading it provides all the parameters but files are different. – ReliantAshish Dec 24 '14 at 12:51
  • possible duplicate of [Best way to do multiple constructors in PHP](http://stackoverflow.com/questions/1699796/best-way-to-do-multiple-constructors-in-php) – RandomSeed Dec 24 '14 at 13:11

4 Answers4

2

PHP doesn't support constructor overloading. Here's a little hack to understand and use overloaded constructors. You can use func_get_args() to retrieve and inspect the passed arguments and make a call to the custom overloaded __construct functions with the matched parameters.

class Construct{ 
    function __construct() { 
        $a = func_get_args();   // get constructor parameters
        $i = func_num_args();   // count(func_get_args())

        if (method_exists($this,$f='__construct'.$i)) { 

            /*
            *   Call to the overloaded __construct function
            */
            call_user_func_array(array($this,$f),$a); 
        } 
    } 

    function __construct1($a1) { 
       echo('__construct with 1 param called: '.$a1); 
    } 

    function __construct2($a1,$a2) { 
        echo('__construct with 2 params called: '.$a1.','.$a2); 
    } 

    function __construct3($a1,$a2,$a3) { 
        echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3); 
    } 
} 

$obj    = new Construct('one');     // Prints __construct with 1 param
$obj2   = new Construct('one','two');   // Prints __construct with 2 params
$obj3   = new Construct('one','two','three'); // Prints __construct with 3 params
Waleed Ahmad
  • 2,184
  • 4
  • 21
  • 23
0

I think the best way is to use helpers methods, like :

$employee = Employee::withName($name);

if you are interested in this method, check out the full answer provided by @Kris here.

Community
  • 1
  • 1
teeyo
  • 3,665
  • 3
  • 22
  • 37
0

Well first of all you have more than one question to your answer.

a) in order to provide you with the ability of having the "constructor" in multiple forms(but still limited) see the following example;

  class Foo{
        public $dmg;
        public $speed;
        public function __construct($dmg = '2', $speed = '3'){
            $this->dmg = $dmg;
            $this->speed = $speed;
            }
    }

    $a = new Foo();
    echo $a->speed."\n"; //3
    $a = new Foo(6,6);
    echo $a->speed."\n"; //6

b) your function return_employee_data does not depend on any internals from the class, this way if you want to use it outside you can make it static ( in front of the definition write static ) so you can use it as Employee::return_employee_data($id); from anywhere you have included the library with this class

Ţîgan Ion
  • 176
  • 1
  • 12
0

PHP indeed does not support overloading, but rather gives you the ability to have optional arguments for your methods. You could manually expand your constructor function to include multiple types of constructors, like this:

public function __construct($fn = null, $ln = null, $dob = null)
{
   if($fn === null && $ln === null && $dob === null ) {
      $this->constructNothing();
   }
   else {
     $this->constructFull($fn,$ln,$dob);
   }
}

private function constructFull( $fn, $ln, $dob ) {
   $this->first_name = $fn;
   $this->last_name = $ln;
   $this->date_of_birth = $dob;
}

private function constructNothing() {
   // whatever you need goes here
}

Now you can call new Employee() and get a special constructor from it.

(By the way, PHP will not complain if you call a function with too few arguments; it will simply pass null for all of them. So if your new constructor will do nothing, it'll work as you have it now as it will simply assign null to each property, which is the default value anyway)

Erik
  • 3,598
  • 14
  • 29