我会说两种语法都是完全一样的东西…
编辑:写完余下的答案后,实际上这并不完全正确^^这取决于你所声明的内容;看这两个例子:
如果您将Foo定义为构造函数,并使用__construct调用它,它似乎正在运行;以下代码:
class Foo {
public function Foo() {
var_dump('blah');
}
}
class Bar extends Foo {
public function Bar() {
parent::__construct();
}
}
$a = new Bar();
输出
string 'blah' (length=4)
所以,现在都可以了;-)
另一方面,如果定义__construct,并调用Foo,就像这样:
class Foo {
public function __construct() {
var_dump('blah');
}
}
class Bar extends Foo {
public function Bar() {
parent::Foo();
}
}
$a = new Bar();
它会给你一个致命的错误:
Fatal error: Call to undefined method Foo::foo()
所以,如果你的类被声明为旧的语法,你可以称之为两种方式;如果它使用新的(PHP5)语法定义,则必须使用新的语法 – 这是有道理的,以后:-)
BTW,如果你想要某种“真实的证明”,你可以尝试使用Vulcan Logic Disassembler,这将给你一个PHP脚本对应的操作码.
编辑后评论
我已经使用两种语法上传了使用VLD的输出:
– vld-construct-new.txt:当声明__construct,并调用__construct.
– vld-construct-old.txt:当声明Foo,并调用__construct.
在两个文件之间做差异,这是我得到的:
$diff vld-construct-old.txt vld-construct-new.txt
25c25
< Function foo:
---
> Function __construct:
29c29
< function name: Foo
---
> function name: __construct
44c44
< End of function foo.
---
> End of function __construct.
71c71
< Function foo:
---
> Function __construct:
75c75
< function name: Foo
---
> function name: __construct
90c90
< End of function foo.
---
> End of function __construct.
(统一差距要长得多,所以我会坚持使用默认的“diff”格式)
因此,拆卸的操作码的唯一区别是功能的名称;在Foo类和Bar类中(继承Foo类的__construct / Foo方法).
我真的会说的是:
>如果你正在编写PHP 5代码(而且在2009年,我真诚地希望你做^^),那么只需使用__construct语法
>你必须保留一些旧的PHP 4代码,你不能迁移到PHP 5(你应该),然后使用Foo语法…
For backwards compatibility, if PHP 5
cannot find a __construct() function
for a given class, it will search for
the old-style constructor function, by
the name of the class.
Effectively, it means that the only
case that would have compatibility
issues is if the class had a method
named __construct() which was used
for different semantics.
所以,我真的认为没有那么大的区别:-)
你遇到某种奇怪的问题,你认为是由两种语法之间的区别引起的?