有一定的差别,是:
#1:类没有被正式视为具有这些属性,如果你只在构造函数中
Example定义它们:
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
}
More examples关于该约束在PHP手册提供。
#3:对于在构造函数中初始化值,如果一个派生类忽略调用父类的构造结果可能是意外
Example:
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-14 00:46:05
Jon
感谢Jon,我非常感谢你所有的代码示例以及指向php记事本的链接 – user784637