2013-08-03 81 views
0
function file_get_contents_new($url, $wait = 3) { 
    if (http_response($url, '200', $wait)) { 
     return file_get_contents($url); 
    } else { 
     return FALSE; 
    } 
} 
function OO_chart($query_stub, $length) 
    { 
     $key = $this->OO_charts_key; 
     $url_api = "https://api.oocharts.com/v1/query.jsonp?query={$query_stub}&key={$key}&start={$length}"; 
     $json = file_get_contents_new($url_api); 
     if (file_get_contents_new($url_api) ? (string) true : (bool) false && (bool) $this->OO_active) { 
      return json_decode($json, TRUE); 
     } else { 
      $msg = new Messages(); 
      $msg->add('e', 'JSON error. Check OOcharts api.'); 
      redirect('index.php'); 
     } 
    } 

將file_get_contents_new($ url_api)? (字符串)true:(布爾)以這種方式做假工作? 如在,它將評估爲true如果函數輸出string, 並且它將評估爲false如果函數是bool三元運算符評估爲真如果字符串或假如果布爾

+2

你試過了嗎? – 1234567

+0

看到我的回答,我建議使用其他類型評估。 – 1234567

回答

0

file_get_contents_new()失敗時返回讀取數據或FALSE $content==false將返回true。

http://php.net/manual/en/function.file-get-contents.php

那麼,爲什麼複雜的事情?這應該工作。但是,只有一個辦法,找出...

$contents = file_get_contents_new($url_api); 

    if (($contents!==false) && (bool) $this->OO_active) { 
     return json_decode($json, TRUE); 
    } 

此外,我不喜歡(bool)分配。是不是該參數應該是boolean已經?

並回答你的問題 - 是一個if語句中的三元運算符應該工作。但它很難測試,調試,維護,並使您的代碼不易讀。我不喜歡這樣使用它。

1

不,那不行。翻譯回一個正常的if/else它更容易解釋爲什麼這不會工作:

if(!file_get_contents($file)){ 
    // the file_get_contents function returned false, so something went wrong 
} 
else{ 
    // the if-condition was not met, so the else will do its job 
    // The problem is that we got the content in the if-condition, and not in a variable 
    // therefor we can not do anything with its contents this way 
    echo "It did work, but I have no way of knowing the contents"; 
} 

一個解決辦法是這樣的:

$content = file_get_contents($file); 
$content = $content===false ? 'No content' : $content; // rewrite if file_get_contents returns false 

有點小心與三元檢查,使用三聯等於跡象。在某些情況下,文件的內容可能是'假'。檢查是否因爲它具有相同的值(但不是同一類型(串/布爾)

+0

'$ contents = file_get_contents($ file);如果($ contents!== FALSE){//做的東西}其他{「它沒有工作!」; } ??? – AmazingDreams

+0

我給了簡單的代碼來解釋思路,你需要熟悉它 – Martijn

+0

'它確實有效,但我無法知道內容=== FALSE – AmazingDreams

2

。您嘗試在if(){}else{}語句中鍵入-juggle(切換變量的數據類型)。

正確的方法做,這是你的if語句更改爲以下:

if (is_string(file_get_contents_new($url_api)) && is_bool($this->OO_active)) { 
    return json_decode($json, TRUE); 
} else { 
    $msg = new Messages(); 
    $msg->add('e', 'JSON error. Check OOcharts api.'); 
    redirect('index.php'); 
} 

現在,你看到了,我在PHP中利用的is_bool()is_string()功能。如果你的函數file_get_contents_new返回一個字符串,它將計算爲真,並檢查$this->OO_active是否是一個布爾值。如果您的file_get_contents_new函數返回布爾值(表示它不是字符串),它將立即執行您的else{}語句,因爲您的if條件必須爲真(因爲運算符爲&&/and),並且如果其中一個條件返回假或斷鏈,它將移動到else聲明。