2016-11-04 20 views
0
上課的時候

所以我有一個簡單的類,在這裏:意想不到的功能,它存在,試圖實例

<?php 
class MyClass 
{ 
    private $key; 
    private $location; 

    function __construct($par1Key, $par2Location) 
    { 
     if(empty($par1Key) || empty($par2Location)) 
      throw new Exception("One or more parameters were left empty."); 
     //do stuff 
    } 

    public static function new($par1Key, $par2Location) { 
     try { 
      return new MyClass($par1Key, $par2Location); 
     } catch (Exception $e) { 
      return null; 
     } 
    } 
} 
?> 

現在我想,當我需要它在我的項目頁面做到這一點:

<?php 
    require('myclass.php'); 

    function getInfo($location) { 
     $key = 'xyzabc123'; 
     $class = MyClass::new($key, $location); 

     return $class->myMethod(); 
    } 
?> 

但它引發錯誤:

Parse error: syntax error, unexpected 'new' (T_NEW) in PATHTOFILE/file.php on line 6.

我怎樣才能避免這個錯誤?

+4

我認爲'new'是一個保留關鍵字,您不能將其用作函數名稱。 – Phiter

+0

如果我的答案有幫助,請將其視爲已接受,以便其他人可以在將來看到它。 – Phiter

回答

1

new是PHP中的reserved keywords之一,您不能將其用作函數或變量名稱。

enter image description here

更改您的函數名稱到別的東西,像createNew或東西,它會工作。

0

感謝Philter Fernandes,該問題指出new是保留關鍵字。我改變了方法名稱,現在它可以工作。

相關問題