2014-01-18 59 views
-4

在此tutorial中解釋瞭如何在PHP中創建RESTful API。我的問題與標題爲的部分中的代碼有關。創建具體的API。我複製/粘貼NetBeans中的代碼,我得到關於該代碼的消息:找不到代碼中的語法錯誤在哪裏

$this->User = $User; 

我從編輯得到的消息是變量$這是意外。我找不到這裏的錯誤。 謝謝。

這裏是代碼,它出現在編輯器:

class MyAPI extends API 
{ 
protected $User; 

public function __construct($request, $origin) { 
    parent::__construct($request); 

    // Abstracted out for example 
    $APIKey = new Models\APIKey(); 
    $User = new Models\User(); 

    if (!array_key_exists('apiKey', $this->request)) { 
     throw new Exception('No API Key provided'); 
    } else if (!$APIKey->verifyKey($this->request['apiKey'], $origin)) { 
     throw new Exception('Invalid API Key'); 
    } else if (array_key_exists('token', $this->request) && 
     !$User->get('token', $this->request['token'])) 

     throw new Exception('Invalid User Token'); 
    } 

    $this->User = $User; 
    } 

/** 
* Example of an Endpoint 
*/ 
protected function example() { 
    if ($this->method == 'GET') { 
     return "Your name is " . $this->User->name; 
    } else { 
     return "Only accepts GET requests"; 
    } 
} 
} 
+0

在該行之前添加代碼,可能是您錯過了';'或'}'。這就是爲什麼'$ this'是意外的原因 – Niels

+0

請張貼更多的代碼(錯誤周圍5-10行)。 – Jonathan

+0

什麼代碼?你的意思是; } –

回答

3

你缺少一個{

} else if (array_key_exists('token', $this->request) && 
     !$User->get('token', $this->request['token'])) // HERE 
+0

是的..那是錯誤,謝謝 –

0

$this只允許當你是一個類的內部。

您必須在課外使用$this,因此出現錯誤。編輯

沒有開括號{

else if (array_key_exists('token', $this->request) && 
     !$User->get('token', $this->request['token'])) 
+0

不,$ this是INSIDE類,所以這不一定是錯誤的來源 –

+1

發佈更多的代碼,然後..你是什麼確切的錯誤? – Manu

+0

我不能真正複製/粘貼編輯器中的錯誤消息,因爲它是baloon窗口...但是這裏是說:不明確變量$ this after} –

0

替換此,您沒有正確關閉else if條件_construct功能

  public function __construct($request, $origin) { 
       parent::__construct($request); 

       // Abstracted out for example 
       $APIKey = new Models\APIKey(); 
       $User = new Models\User(); 

       if (!array_key_exists('apiKey', $this->request)) { 
        throw new Exception('No API Key provided'); 
       } else if (!$APIKey->verifyKey($this->request['apiKey'], $origin)) { 
        throw new Exception('Invalid API Key'); 
       } else if (array_key_exists('token', $this->request) && !$User->get('token', $this->request['token'])){   
        throw new Exception('Invalid User Token');      
       } 

      $this->User = $User; 
     }