简体   繁体   中英

Type hinting in PHP constructors?

Is there anything to stop me from type hinting like this within the __construct() parentheses?

<?php

    class SomeClass extends BaseClass {

        public function __construct(array $someArray) {

            parent::__construct($someArray);
        }

Or can I only do it like this?

<?php

    class SomeClass extends BaseClass {

        public function __construct($someArray = array()) {

            parent::__construct($someArray);
        }

Edit:

This is what works: (Thanks @hakra and @Leigh)

<?php

    class SomeClass extends BaseClass {

        public function __construct( array $someArray = NULL ) {

            parent::__construct( (array) $someArray);
        }

To me it looks nice and clean and I know exactly what it supposed to mean.

This is type hinting with no default, stating that a parameter must be given, and it's type must be an array

public function __construct(array $someArray) {


This is providing the default value for the argument if no parameter is passed, without a typehint.

public function __construct($someArray = array()) {


They are two different things.

In the second instance you can call the function with no parameters and it will work, but the first will not.

If you want, you can combine the two, to specify an default and specify the required type.

public function __construct(array $someArray = array()) {

Or as @hakre has stated, you can do:

public function __construct(array $someArray = NULL) {

You can do so:

public function __construct(array $someArray = NULL)
{
    $someArray = (array) $someArray;
    parent::__construct($someArray);
    ...

The case here is to make use of the = NULL exception of the rule. The next line:

    $someArray = (array) $someArray;

is just some shorthand to convert NULL into an empty array and otherwise leave the array an array as-is (a so called cast Docs to array ):

Converting NULL to an array results in an empty array.

(from: Converting to array Docs )

Sure you could write it even shorter:

public function __construct(array $someArray = NULL)
{
    parent::__construct((array) $someArray);
}

but it does not explain it that well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM