2017-02-25 35 views
0

我有PHP 7和我收到以下錯誤:PHP 7棄用構造問題

[25-Feb-2017 01:29:12 UTC] PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; my_function has a deprecated constructor in /function.php on line 8

class my_function{ 
     ... 
     public function my_function(){} 
     ... 
} 

更新之前,我從來沒有任何問題。我不知道如何解決這個問題。

有什麼建議嗎?如果我只是改變名字,恐怕會更糟糕。這裏有什麼問題?

謝謝!

+3

替換'公共函數創建my_function()'和'公共職能__construct()' –

回答

2

在一個很舊版本的PHP(PHP 4,要準確),其作爲類作爲構造具有相同名稱的函數名。

也就是說,如果你打電話給new my_function(),類中的方法my_function將被調用任何參數。

現在,如果您使用my_function作爲構造函數,則替代方法是將其重命名爲__construct。無論何時啓動實例,這都會起作用。

另一方面,如果您碰巧有一個函數與類共享一個名稱,並且不依賴它作爲構造函數,那麼您應該能夠完全忽略該警告,因爲它引用了不推薦使用的功能。

編輯:如果它是第二個方案,確保還添加了一個public function __construct(),如果有沒有一個人也沒有。離開它空是好的,但僅僅有這將確保PHP不無意中嘗試調用my_function的實例,爲__construct將優先考慮。

例子:

<?php 

class Foo 
{ 
    //DEPRECATED CONSTRUCTOR SYNTAX (Don't try this at home.) 
    public function Foo() 
    { 
     echo "Foo named constructor\n"; 
    } 
} 

$f = new Foo(); 
//Foo named constructor 

class Bar 
{ 
    public function __construct() 
    { 
     echo "Bar constructor\n"; 
    } 

    public function Bar() 
    { 
     echo "Bar function\n"; 
    } 
} 

$b = new Bar(); 
//Bar constructor 
$b->Bar(); 
//Bar function 
+0

還不錯的答案,也許你可以提供一個代碼示例是超級額外清楚了嗎? –

+1

那看起來怎麼樣? –

+0

我把評論的公共函數foo(),上面寫着//不要做到這一點是現在已不足夠 –

1

它只是說,約定要離開。應該安全地將其重命名爲__construct。該公約已經出現自PHP 4