我可以用同一种方法调用方法吗?

时间:2015-12-08 16:55:11

标签: php class laravel-5.1 static-methods

我遇到的情况是,如果抛出任何异常,我需要调用相同的方法,以确保我不会复制任何代码。但是,它没有像我想的那样工作。这是相关的代码:

public static function getFolderObject($folder_id)
    {
        $client = new Client('https://api.box.com/{version}/folders', [
            'version' => '2.0',
            'request.options' => [
                'headers' => [
                    'Authorization' => 'Bearer ' . self::getAccessToken(),
                ]
            ]
        ]);

        $request = $client->get($folder_id);

        try {
            $response = $request->send();
            $result = $response->json();

            $files = $result['item_collection']['entries'];
        } catch (BadResponseException $e) {
            $result = $e->getResponse()->getStatusCode();

            if ($result === 401) {
                self::regenerateAccessToken();
                self::getFolderObject();
            }
        }

        return count($files) ? $files : false;
    }

正如您所看到的,我正在调用if条件self::getFolderObject();下的方法方法中的方法,以防止在方法开头的if语句下重复代码。但是,如果我复制代码,它按预期工作。有没有解决方案来实现我的目标?

1 个答案:

答案 0 :(得分:2)

您错过了返回值并指定了folder_id:

public static function getFolderObject($folder_id)
    {
        $client = new Client('https://api.box.com/{version}/folders', [
            'version' => '2.0',
            'request.options' => [
                'headers' => [
                    'Authorization' => 'Bearer ' . self::getAccessToken(),
                ]
            ]
        ]);

        $request = $client->get($folder_id);

        try {
            $response = $request->send();
            $result = $response->json();

            $files = $result['item_collection']['entries'];
        } catch (BadResponseException $e) {
            $result = $e->getResponse()->getStatusCode();

            if ($result === 401) {
                self::regenerateAccessToken();
                return self::getFolderObject($folder_id);
            }
        }

        return count($files) ? $files : false;
    }