2014-01-18 62 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; 
     }