php 方法名和类名相同

<?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来使用其余的方法,
相关文章
相关标签/搜索