2013-05-14 90 views
-1

更新:我得到這個PHP的錯誤:試圖讓該行非對象的屬性: 如果($卡 - >名== $ fileRef){PHP構造函數單PARAM

我使用__construct(x='') { definition }構建一個對象並調用函數$var = new Object('string');

構造函數接收一個字符串,即與相應的'file.php'相關的'文件'。在json文件中有這個類的所有可用file.php的目錄,其中包含目錄信息。

而我正在捕捉一個錯誤,也許與我的語法? ...現在讓我有兩天,想要擺動?

public function __construct($ctitle = '') 
{ 
    $fileRef = $ctitle.'php'; 

    //Get the json card directory 
    $this->cardDirLocation = 'thisismyserver.com/CardDir.json'; 
    $this->cardDir = file_get_contents($this->cardDirLocation); 
    $this->cardArray = json_decode($this->cardDir, true); 


    //Find the card listing from CardDir.json based on form response input and construct a Card class instance or use the main page (default) 
    foreach ($this->cardArray['Cards'] as $key => $val) { //search through each card IS THIS MY ERR?? 
     if ($card->name == $fileRef){ //if the name matches a name in the cardDir.json file 
      //Fill Values 
     } 
        if ($this->title == ''){ //or if there is no title 
      $this->title = 'Get Started at The Home Page'; //refer to default values -> the home page 
      $this->dir = 'cards/start/'; 
      $this->name = 'start.php'; ...etc 

的錯誤:我不能得到$ fileRef變量與JSON文件陣列中的任何東西搭配起來,所以它總是進入「否則,如果」默認。 JSON文件看起來是這樣的:

{"Cards":[{"title":"Something", "name":"file.php", "dir":"somefile/dir/here/" }, {"title":"Different than something", "name":"xfiles.php", "dir":"somefile/dir/there/" ...etc

+0

什麼是輸出行'echo:$ val ['name']'? – 2013-05-14 17:28:48

+0

謝謝這已被回答。 – 2013-05-14 18:14:15

回答

0

您可能要遍歷整個數組返回或設置一個通用的案前。這裏是如何做到這一點:

foreach ($this->cardArray['Cards'] as $card) { 
    if ($card->name == $fileRef) { 
    // Your success actions here 
    return true; 
    } 
} 
// Your failure actions here. This will only be reached if the foreach loop found nothing. 
+0

Explosion Pills:調試回聲語句輸出start.php(我想要的)它在foreach中沒有匹配。 Sabrina:你是絕對正確的。我犯了一個人爲錯誤,你發現了這一點,就像我剛發佈這個問題一樣。我會做出一些改變,並保持張貼* – 2013-05-14 17:41:43

+0

你的start.php輸出是在foreach之後完成的,不管發生了什麼。否則,你的foreach只會跨越數組的第一個元素。 – 2013-05-14 17:44:14

+0

問題出在if else和我想要輸出的語法上。 我也必須訪問解碼的json,因爲這樣的 $ this-> cardArray ['Cards']作爲$ card => $ val ... $ this-> name = $ val ['name']; – 2013-05-14 18:15:24