简体   繁体   中英

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

I'm trying to use the Wordnik PHP API and I'm having some trouble. I tried to use the getDefinitions method but it returns an error: Notice: Trying to get property of non-object in C:\\xampp\\htdocs\\index.php on line 18 .

Here is the following code:

<!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>

I think your notice (not really an error in the php world) does not come from the $word1 = $wordApi->getDefinitions($word1, null, null); but from print $word1->text; is it possible?

If you check the 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

You can see that getDefinitions(...) return an array of Definition or null.

One thing is sure, you cannot get the ->text property from $word1 but from one of these indexes if the return is valid. Try $word1[0]->text

Anyway you should also handle the case where the return of getDefinitions(...) return an empty array or null.

This sample code might help you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM