开发者

Why define type of instance var in the __construct rather than in the var list?

I am reading some code that looks like that:

Class_Menu.php:

<?php
    class Menu {
        private $label;
        private $link;
开发者_Go百科        private $args;

        function __construct($label, $link, $args=array()) {
            $this->label=$label;
            $this->link=$link;
            $this->args=$args;
        }
...

Note how $args is defined as an array in the __construct. Why would one choose this approach rather than define $args in the var list:

<?php
    class Menu {
        private $label;
        private $link;
        private $args=array();

        function __construct($label, $link, $args) {
            $this->label=$label;
            $this->link=$link;
            $this->args=$args;
        }
...


In the first example, $args is optional. The constructor can be called with only 2 arguments for $label and $link, and $args will be defined as an empty array.

In the second example, the $args parameter is required.

(opinion): I would have left $args = array() in the constructor AND when declaring the property so it's easy to tell at a glance what type of var $args is.

<?php
    class Menu {
        private $label;
        private $link;
        private $args = array();

        function __construct($label, $link, $args=array()) {
            $this->label=$label;
            $this->link=$link;
            $this->args=$args;
        }


One allows you to use the constructor with either two or three arguments (as the third is optional).

The other does not.

Why not read the manual entry on function arguments?


That just makes $args optional. If the constructor's called as new Menu('a', 'b'), then args will be defined as an empty array and not raise an error about the missing argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜