php 初始化父构造函数,使用旧/新语法调用PHP父构造函数

这篇博客探讨了PHP5中__construct构造函数与旧的类名构造函数之间的差异。作者通过实例展示了当使用不同语法定义和调用构造函数时,代码行为的变化,并提到了操作码级别的差异。文章指出,在PHP5中,如果类未定义__construct,则会搜索旧的构造函数。最后,作者建议在编写PHP5代码时使用__construct语法,以保持一致性。
摘要由CSDN通过智能技术生成

我会说两种语法都是完全一样的东西…

编辑:写完余下的答案后,实际上这并不完全正确^^这取决于你所声明的内容;看这两个例子:

如果您将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.

所以,我真的认为没有那么大的区别:-)

你遇到某种奇怪的问题,你认为是由两种语法之间的区别引起的?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值