0

While reading about PHP constructors, I came across the below example on this page.

<?php
    class MyClass {
        // use a unique id for each derived constructor,
        // and use a null reference to an array, 
        // for optional parameters
        function __construct($id="", $args=null) {
            // parent constructor called first ALWAYS
            /*Remaining code here*/
        }
    }

I am not able to understand why $id is set to "" and $args to null. When would I use something like this? Why can't we just use function __construct($id, $args) {.

1
  • 1
    when you instantiate your class MyClass you can either instantiate with parameter or without them.. when you do $myclass = new MyClass().. it will take those default parameters $id="" and $args= null.. but when you instantiate $myclass = new MyClass(2, array(1,2)).. it will take $id = 2 and $args = array(1,2)... Commented Feb 9, 2013 at 21:53

3 Answers 3

4

Those are default arguments. When they are not provided by the caller, they will be set to those values. Otherwise, it will be set to the caller's values.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help. Coming from a Java background, this was a bit different.
@rgamber: In Java, the same sort of thing can be achieved more verbosely by overloading the constructor and calling a different constructor from within that constructor.
3

So that both $x = MyClass("12", array(1, 2, 3)) and $y = MyClass() are valid.

Without those default arguments, MyClass() would produce an error.

Comments

3

Those are default argument values.

This means that you can call the constructor without passing any paramaters and then the constructor will add those values to the arguments.

Thus you could create an instance like this:

$mc = MyClass();

So when could this be useful? Well suppose you have a class that usually have the same parameters, let's say you have the class Door which usually is of the type normal. Then you could omit passing that value, but then sometimes you want a Door which is of the type safe then you'd want to pass that. To clarify:

class Door {
  private $door_type;
  public function __construct($type='normal') {
    $this->door_type = $type;
  }
}

//Create a 'normal' door
$normal_door = new Door();
$normal_door = new Door('normal'); //the same as above

//Create a 'safe' door
$safe_door = new Door('safe');

This example is obviously not how you'd implement it in the real world but I hope you see the use of it.

As a note, not all languages support this, Java for example does not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.