Wordnik "Trying to get property of non-object" 尝试 getDefinitions 时出错

Wordnik "Trying to get property of non-object" Error when trying getDefinitions

我正在尝试使用 Wordnik PHP API,但遇到了一些问题。我尝试使用 getDefinitions 方法,但它 returns 出现错误:Notice: Trying to get property of non-object in C:\xampp\htdocs\index.php on line 18.

下面是代码:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form method="post">
            <input type="text" placeholder="First Word" name="word1">
            <input type="submit" placeholder="Compare">
        </form>
        <?php
            require('./wordnik/Swagger.php');
            $APIKey = '342eac9900e703079b0050d5f7008eab962195189e75bfbcb';
            $client = new APIClient($APIKey, 'http://api.wordnik.com/v4');

            $word1 = $_POST['word1'];
            $wordApi = new WordApi($client);
            $word1 = $wordApi->getDefinitions($word1, null, null);
            print $word1->text;
        ?>
    </body>
</html>

我认为您的通知(在 php 世界中并不是真正的错误)不是来自 $word1 = $wordApi->getDefinitions($word1, null, null);,而是来自 print $word1->text;,这可能吗?

如果你查看 WorldApi class :

https://github.com/wordnik/wordnik-php/blob/master/wordnik/WordApi.php#L182 https://github.com/wordnik/wordnik-php/blob/master/wordnik/WordApi.php#L138

你可以看到 getDefinitions(...) return 一个 Definition 或 null 的数组。

有一件事是肯定的,如果 return 有效,您不能从 $word1 中获取 ->text 属性,而是从其中一个索引中获取。尝试 $word1[0]->text

无论如何,您还应该处理 getDefinitions(...) return 的 return 为空数组或 null 的情况。

此示例代码可能对您有所帮助:

apiUrl = 'http://api.wordnik.com/v4'
apiKey = 'YOURKEYHERE'
client = swagger.ApiClient(apiKey, apiUrl)
wordApi = WordApi.WordApi(client)
res = wordApi.getWord('cat')
res2 = wordApi.getDefinitions('cat')
assert res, 'null getWord result'
assert res.word == 'cat', 'word should be "cat"'
print res.word
print dir(res2[0])
print res2[0].partOfSpeech