[英]Wordnik “Trying to get property of non-object” Error when trying getDefinitions
我正在嘗試使用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世界中的錯誤)不是來自$word1 = $wordApi->getDefinitions($word1, null, null);
但從print $word1->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
獲得->text
屬性,而是從這些索引之一中獲得。 嘗試$word1[0]->text
無論如何,您還應該處理以下情況: getDefinitions(...)
返回返回空數組或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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.