php 类名相同,php 方法名和类名相同

本文探讨了PHP中类的方法名与其类名相同的情况,指出在未来的版本中这将不再被视为构造函数。通过示例展示了类的继承调用过程,解释了`self`, `parent`关键字的使用,并强调了在实际项目中灵活运用类方法调用的重要性。同时,注意到PHP7中此类构造函数仍有效,但已废弃并发出警告。
摘要由CSDN通过智能技术生成

class foo

{

public function foo()

{

echo __CLASS__."\r\n";

}

}

class foo_bar extends foo

{

public function foo_bar()

{

echo __CLASS__."\r\n";

}

}

class foo_bar_baz extends foo_bar

{

public function foo_bar_baz()

{

echo __CLASS__."\r\n";

}

public function call()

{

self::foo_bar_baz();

parent::foo_bar();

foo::foo();

}

}

$obj = new foo_bar_baz();

$obj->call();

// output

λ php demo_class12.php

PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo has a deprecated constructor in D:\localhost\WWW\demo\demo_class12.php on line 2

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo has a deprecated constructor in D:\localhost\WWW\demo\demo_class12.php on line 2

PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo_bar has a deprecated constructor in D:\localhost\WWW\demo\demo_class12.php on line 12

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo_bar has a deprecated constructor in D:\localhost\WWW\demo\demo_class12.php on line 12

PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo_bar_baz has a deprecated constructor in D:\localhost\WWW\demo\demo_class12.php on line 22

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo_bar_baz has a deprecated constructor in D:\localhost\WWW\demo\demo_class12.php on line 22

foo_bar_baz

foo_bar_baz

foo_bar

foo

//

Deprecated : 不赞成/弃用

如果一个类的名称和其中的一个方法名称是一致的, 不会被当做是构造函数, 在php的未来的版本中.

实际的测试结果是: 在php7版本中, 如果类名和方法名是一致, 还是会将方法名当做是构造函数去处理,

// 实际的demo 请参考php 手册中. 类与对象--> 对象继承

该实例说明了2个问题 ;

1 通过警告信息得到的内容, 如果一个类中的方法方法名称和类名称是相同的, 在php中是不会被当做构造函数的,

在c++中是这样的,

2 正常在项目中调用父类的方法用parent关键词, 在本实例中使用范围解析符来处理,脱离了static 生命周期的描述.

3 在实际的项目中,可以灵活的使用self/parent/className::, 处理类间方法的调用.

4 不是一个种非继承关系, 可以使用static来使用其他的方法,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值