将参数值明确指定为默认值

时间:2015-12-16 00:57:50

标签: php oop

这是我想要实现的一个例子:

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 的情况是否相同。

1 个答案:

答案 0 :(得分:2)

如果你想使用默认值,那么它应该在最后。但是,如果您知道正在使用的数据类型,则可以将值设置为通常不会传递的值。然后在构造函数中,您可以检查它并将其替换为默认值。

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.否则,它会将其设置为传递的任何内容。