2015-12-29 102 views
14

我收到此錯誤:PHP7 method_exists未捕獲的錯誤:函數名稱必須是一個字符串

Fatal error: Uncaught Error: Function name must be a string in

對於此代碼:

if (function_exists($item['function'])) { 
    $item['function']($item, $default); 
} elseif (method_exists($this, $item['function'])) { 
    $this->$item['function']($item, $default); 
} 

我知道,改變的代碼

if (function_exists($item['function'])) { 
    $item['function']($item, $default); 
} elseif (method_exists($this,$item['function'])) { 
    $this->{$item['function']}($item, $default); 
} 

解決了這個錯誤,但我的問題是,應該這條線

$item['function']($item, $default); 

也可轉變成

{$item['function']}($item, $default); 

還是可以保持原樣?

+0

你確定這個項目功能鍵已設置,它的字符串?在使用之前添加檢查。 – Svetoslav

回答

-1

並改用(無)數組。

@Svetlio,不適用於舊版本,但兼容!

爲什麼人們誤解了這個?你們都懶得再寫一行作業了?

+2

在較早的PHP版本中是的,但在7中並不需要。 – Svetoslav

21

這是訂單的評估,由於incompatible changes處理間接變量和方法:

Changes to the handling of indirect variables, properties, and methods

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluaiton has changed.

不,你不必改變這一行:

$item['function']($item, $default); 

因爲這裏沒有特別的評估,它只會使用數組元素作爲函數名稱並調用函數。你可以改變它,代碼仍然可以正常工作,但這不是必須的。

但是,正如你已經正確地做,你必須改變:

$this->$item['function']($item, $default); 

到:

$this->{$item['function']}($item, $default); 
     ↑     ↑ 

既然你可以在這個table看到:

     Old and new evaluation of indirect expressions 
     Expression   PHP 5 interpretation   PHP 7 interpretation 
------------------------------------------------------------------------------- 
    $$foo['bar']['baz'] |  ${$foo['bar']['baz']} | ($$foo)['bar']['baz'] 
    $foo->$bar['baz'] |  $foo->{$bar['baz']} | ($foo->$bar)['baz'] 
    $foo->$bar['baz']() |  $foo->{$bar['baz']}() | ($foo->$bar)['baz']() 
    Foo::$bar['baz']() |  Foo::{$bar['baz']}() | (Foo::$bar)['baz']() 

PHP 7將假設你首先想訪問一個對象屬性,然後你想從中訪問一個索引屬性,並將其值用作方法名稱來調用方法(從左到右的順序)。

要使用變量和索引作爲屬性名稱,必須使用大括號來表示該屬性。

相關問題