下面是我试图实现的一个示例:
class Employee {
private $empno;
private $ename;
private $job;
private $mgr;
private $hiredate;
private $sal;
private $comm;
private $deptno;
function __construct($empno = 100, $ename = "Default E Name",
$job = "nothing", $mgr = null, $hiredate = "1970-01-01",
$sal = 0, $comm = 0, $deptno = 0) {
$this->empno = $empno;
$this->ename = $ename;
$this->job = $job;
$this->mgr = $mgr;
$this->hiredate = $hiredate;
$this->sal = $sal;
$this->comm = $comm;
$this->deptno = $deptno;
}
}
我想用这种方式创建一个对象:
$employee = new Employee($e_number, $e_name, $e_function,
DEFAULT, $e_date, $e_salaire, DEFAULT, $e_dept);
// Where 'DEFAULT' is used to specify that the default value of the argument shall be used
如何明确告诉class
的构造函数我希望使用默认值?
我知道,对于这个例子,在C++中,您应该将带有默认值的参数留在函数的签名的末尾,但我不知道PHP是否也是如此。
如果您想使用默认值,那么是的,它应该在末尾。但是,如果您知道正在处理的数据类型,则可以将该值设置为通常不会传递的值。然后在构造函数中,您可以检查它并将其替换为默认值。
function __construct($empno = 100, $ename = "Default E Name", $job = "nothing", $mgr = null, $hiredate = "1970-01-01", $sal = 0, $comm = 0, $deptno = 0) {
$this->empno = $empno;
$this->ename = $ename;
$this->job = $job;
$this->mgr = $mgr;
$this->hiredate = $hiredate;
$this->sal = $sal;
if ($comm == "$$") {
$this->comm = 0;
} else {
$this->comm = $comm;
}
$this->deptno = $deptno;
}
因此,在本例中,如果将$$
作为参数传递,它将把$comm
的值设置为0。否则,它会将其设置为传递的内容。