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來使用其餘的方法,
相關文章
相關標籤/搜索