2012-03-26 66 views
1

在數組的構建過程中,我試圖調用一個函數,checkIfNodeExists()。 PHP執行這個函數並給了我預期的結果,但他仍然給我一個「通知」,我不想在我的代碼中出現任何類型的錯誤。數組中的調用函數(PHP)

function checkIfNodeExists($input) { 
    if (isset($input)) { 
     return (string) $input; 
    } else { 
     return 'null'; 
    } 
} 

$array['sections'][] = array (
    'ident'  => $section->attributes()->ident, 
    'title'  => $section->attributes()->title, 
    'objective' => checkIfNodeExists($section->objectives->material->mattext) 
); 

注意:試圖在xx線獲得非對象的財產/var/www/OLAT_Connection/QTI-XML-Parser.php現在

,如果我檢查是否「客觀的」 OUTSIDE存在該陣列,PHP不給我一個通知。但是,這將導致更多的代碼,因爲我有一個額外的variabele工作和更多的IF結構等等...

有無需添加額外的代碼太行任何其他可能性?

+0

確保$本條> objectives->材料 - > mattext正常啓動和界定。請注意,更多的代碼不一定更糟! – 2012-03-26 09:02:01

+0

也許你應該在調用checkIfNodeExists之前檢查isset – Fivell 2012-03-26 09:11:33

回答

1

似乎$section->objectives->material->mattext不正確定義。我會開始在那裏看看你是否有錯誤的對象的初始化。

如果您發佈了更多代碼,那麼我們可以在此腳本中看到究竟發生了什麼,這會更好。

解決方案可能需要更多的代碼(儘管在這種情況下不太可能),但這絕不是壞事。較少的代碼不一定更好或更高效!顯然,這不用說,更少的代碼會(大部分時間)執行得更快,但這並不使它更安全的或有效

UPDATE

您可以簡單地這樣做而不是調用另一個函數:

'objective' => isset($section->objectives->material->mattext) ? (string)$section->objectives->material->mattext : null 

我沒有測試過這一點,可以不記得你是否可以內嵌在條件語句,因此不能肯定是否會工作,但如果這樣做,那麼這將是更有效的,而且它少代碼!

+1

好的哈利路亞,有條件的作品。但我明白,更多的代碼不一定是壞的。謝謝! – 2012-03-26 09:25:14

+0

很高興我可以幫助,享受! :-) – 2012-03-26 09:25:58

0

如果添加 「@」,當你調用函數的錯誤都沒有表現出

function checkIfNodeExists($input) { 
    if (isset($input)) { 
     return (string) $input; 
    } else { 
     return 'null'; 
    } 
} 

$array['sections'][] = array (
    'ident'  => $section->attributes()->ident, 
    'title'  => $section->attributes()->title, 
    'objective' => @checkIfNodeExists($section->objectives->material->mattext) 
); 
+2

是的,但這只是壓制錯誤。該功能沒有做他想做的事情,所以這不會對它進行排序! – 2012-03-26 09:04:58

0

定義$本條> objectives->材料 - > mattext

2

的問題是,當你調用checkIfNodeExists你把它的值,並通過發送它的價值也執行該值。所以isset()將工作結果的表達式$section->objectives->material->mattext不是表達式本身

這會工作:

$array['sections'][] = array (
    'ident'  => $section->attributes()->ident, 
    'title'  => $section->attributes()->title, 
    'objective' => isset($section->objectives->material->mattext) ? (string)$section->objectives->material->mattext : 'null' 
);