php 方法名和类名相同

本文探讨了PHP中类的构造函数与方法调用的问题,特别是当类名与方法名相同的情况。演示了如何使用self、parent及类名解析符进行方法调用,并讨论了在PHP未来版本中类名与方法名冲突的弃用警告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
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来使用其他的方法,

 

转载于:https://my.oschina.net/u/1579560/blog/1486722

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值