如果构造函数重载是不可能的,那么我如何在 PHP 中创建具有不同参数的对象


If constructor overloading is not possible then how can i create objects with different parameters in PHP?

这是员工.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;
}

}

当我在其他文件中需要这个类时,说xyz.php只是为了

return_employee_data($employee_id);

我必须在该文件中创建一个对象,例如

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

所以我不能像这样return_employee_data($employee_name);运行这个函数

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

如果构造函数重载是不可能的,那么我如何创建具有给定参数且没有任何参数的对象?我还想在其他文件中创建具有变量参数的对象,其中我们只包含类定义,并且文件数据要么不提供数据,要么提供变量数据来创建上述定义的对象?

如果我们不能创建一个对象,我该如何调用它的底层函数来解决任何特定问题?

PHP 不支持构造函数重载。这里有一个小技巧来理解和使用重载的构造函数。您可以使用 func_get_args() 检索和检查传递的参数,并使用匹配的参数调用自定义重载__construct函数。

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

我认为最好的方法是使用辅助方法,例如:

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

如果您对此方法感兴趣,请在此处查看@Kris提供的完整答案。

首先,你的答案不止一个。

a) 为了向您提供具有多种形式的"构造函数"的能力(但仍然有限),请参阅以下示例;

  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)你的函数return_employee_data不依赖于类中的任何内部结构,这样如果你想在外面使用它,你可以让它成为静态的(在定义前面写静态),这样你就可以从任何地方使用它作为Employee::return_employee_data($id);包含这个类的库

PHP 确实不支持重载,而是让你能够为你的方法提供可选的参数。您可以手动扩展构造函数以包含多种类型的构造函数,如下所示:

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
}

现在你可以调用new Employee()并从中获取一个特殊的构造函数。

(顺便说一下,如果你调用一个参数太少的函数,PHP 不会抱怨;它只会为所有参数传递null。因此,如果你的新构造函数什么都不做,它将像你现在一样工作,因为它会简单地为每个属性分配 null,这无论如何都是默认值)