2

Here is an example of what I'm trying to achieve:

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;
    }
}

I want to create an object this way:

$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

How can I explicitly tell the constructor of a class that I want the default value to be used ?

I know that for the example, in C++, you should leave the arguments with default values to the end of the function's signature, but I don't know if it's the same case for PHP too.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • Don't know if it is exactly like C++, but it's similar: http://php.net/manual/en/functions.arguments.php#functions.arguments.default – Rizier123 Dec 16 '15 at 01:00
  • @Rizier123 oh thanks for the link. I checked **example5**. Seems like it's the same behavior as in *C++*. – Mohammed Aouf Zouag Dec 16 '15 at 01:02
  • 1
    Also see: http://stackoverflow.com/q/1066625/3933332 You can't *really* have them in the middle if you want them to be default. – Rizier123 Dec 16 '15 at 01:06

1 Answers1

2

If you want to use the default value then yes it should be at the end. However, if you know the type of data you are working with then you can set the value to something that wouldn't normally be passed. Then in the constructor, you can check for it and just replace it with the default.

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;
    }

So in this example, if you pass $$ as an argument, it will set the value of $comm to 0. Otherwise it sets it to whatever is passed.

RisingSun
  • 1,693
  • 27
  • 45