【问题标题】:Wordnik "Trying to get property of non-object" Error when trying getDefinitions尝试getDefinitions时Wordnik“尝试获取非对象的属性”错误
【发布时间】:2016-11-23 02:31:53
【问题描述】:

我正在尝试使用 Wordnik PHP API,但遇到了一些问题。我尝试使用 getDefinitions 方法,但它返回错误: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 html api wordnik


【解决方案1】:

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

如果您检查 WorldApi 类:

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(...) 返回一个Definition 或null 的数组。

有一点是肯定的,如果返回有效,您不能从 $word1 获得 -&gt;text 属性,而是从这些索引之一获得。试试$word1[0]-&gt;text

无论如何你也应该处理getDefinitions(...)返回一个空数组或null的情况。

【讨论】:

  • 谢谢!我是 PHP 新手,很抱歉我的无能。我今天晚些时候试试。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2021-02-26
    • 2016-09-10
    • 2018-09-26
    • 1970-01-01
    相关资源
    最近更新 更多