找不到代码中语法错误的位置

时间:2014-01-18 18:11:10

标签: php

在此tutorial中,解释了如何在PHP中创建RESTful API。我的问题与标题为创建具体API 的部分中的代码有关。我复制/粘贴Netbeans中的代码,我收到有关此代码的消息:

 $this->User = $User;

我从编辑器得到的消息是变量$ this是意外的。我找不到错误在哪里。 感谢。

以下是编辑器上显示的代码:

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";
    }
 }
 }

3 个答案:

答案 0 :(得分:3)

你错过了{

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

答案 1 :(得分:0)

只有在课堂上时才允许

$this

您必须在课堂外使用$this,因此错误。

编辑:

之后没有开放式大括号{
else if (array_key_exists('token', $this->request) &&
         !$User->get('token', $this->request['token']))

答案 2 :(得分: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;
        }