0

例如,两者之间有区别吗?一个比另一个更受欢迎吗?

Class Node{    
    public $parent = null;
    public $right = null;
    public $left = null;            
    function __construct($data){
        $this->data = $data;                    
    }
}

Class Node{     
    function __construct($data){
        $this->data = $data;      
        $this->parent = null;       
        $this->left = null;       
        $this->right = null;               
    }
}
4

2 回答 2

7

有一定的区别,是的:

#1:如果您只在构造函数中定义它们,则不会正式认为该类具有这些属性

示例

class Foo {
    public $prop = null;
}

class Bar {
    public function __construct() {
        $this->prop = null;
    }
}

var_dump(property_exists('Foo', 'prop')); // true
var_dump(property_exists('Bar', 'prop')); // false

$foo = new Foo;
$bar = new Bar;

var_dump(property_exists($foo, 'prop')); // true
var_dump(property_exists($bar, 'prop')); // true

除了不同的运行时行为之外,使用构造函数将属性“添加”到您的类是不好的形式。如果您希望此类的所有对象都具有该属性(实际上应该是所有时间),那么您还应该正式声明它们。PHP 允许您侥幸逃脱这一事实并不能成为随意的类设计的借口。

#2:您不能从构造函数外部将属性初始化为非常量值

例子:

class Foo {
    public $prop = 'concatenated'.'strings'; // does not compile
}

PHP 手册中提供了有关此约束的更多示例。

#3:对于在构造函数内部初始化的值,如果派生类省略调用父构造函数,结果可能会出乎意料

示例

class Base {
    public $alwaysSet = 1;
    public $notAlwaysSet;

    public function __construct() {
        $this->notAlwaysSet = 1;
    }
}

class Derived extends Base {
    public function __construct() {
        // do not call parent::__construct()
    }
}

$d = new Derived;
var_dump($d->alwaysSet); // 1
var_dump($d->notAlwaysSet); // NULL
于 2013-01-14T00:46:05.633 回答
1

出于几个原因,我更喜欢在构造函数之外声明它们。

  1. 保持我的构造函数清洁
  2. 所以我可以正确记录它们,添加类型信息等
  3. 所以我可以指定访问修饰符,将它们设为私有或受保护,但很少公开
  4. 因此,如果派生类不调用 parent::__construct(),它们也将被声明和/或初始化

即使我需要将它们初始化为非常量值,我也会在我的构造函数之外声明它们并在我的构造函数中初始化它们。

于 2013-01-14T00:47:50.390 回答