Njinx Njinx - 1 year ago 98
HTML Question

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>
<form method="post">
<input type="text" placeholder="First Word" name="word1">
<input type="submit" placeholder="Compare">
$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;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download