Search code examples
phpoopdefault-parameters

Giving a default object to my class method in PHP


I want to pass a DateTimeZone object to my method in my class Test. I have the following code:

class Test {
    function __construct( $timezone_object = new DateTimeZone() ) {
        // Do something with the object passed in my function here
    }
}

Unfortunately, the above doesn't work. It gave me an error. I know I can do the following instead:

class Test {
    function __construct( $timezone_object = NULL ) {
        if ( $timezone_object == NULL)
            $to_be_processed = new DateTimeZone(); // Do something with my variable here
        else 
            $to_be_processed = new DateTimeZone( $timezone_object ); // Do something with the variable here if this one is executed, note that $timezone_object has to be the supported timezone format provided in PHP Manual
    }
}

However, I think that the second choice seems rather unclean. Is there a way to declare my method like the first choice?


Solution

  • If you're just looking for succinct code, you could do

    class Test {
        function __construct( \DateTimeZone $timezone_object = null ) {
            $this->ts = $timezone_object ?? new DateTimeZone();
        }
    }
    

    the double ?? is an if null check. So you have the type hinting which will only allow DateTimeZone or Null value in (so that's safe), then you just assign a new DateTimeZone instance if the argument was null, otherwise, use the passed in value.

    Edit: Found info on default null for PHP 7.1+

    Cannot pass null argument when using type hinting

    So the code could be even more esoteric, with slightly less key strokes

    class Test {
        function __construct( ?\DateTimeZone $timezone_object ) {
            $this->ts = $timezone_object ?? new DateTimeZone();
        }
    }
    

    But in my opinion, this is just horrible.