2012-03-24 42 views
31

我試圖得到一個基於HTML的遞歸目錄列表基於代碼在這裏:「嚴格標準:只有變量應該按引用傳遞」錯誤

http://webdevel.blogspot.in/2008/06/recursive-directory-listing-php.html

代碼運行良好,但它拋出一些錯誤:

嚴格的標準:只有變量應該通過引用 C下通過:\ XAMPP \ htdocs中\ directory5.php在線路34上

規格嚴格S:只有變量應該通過引用 C下通過:\ XAMPP \ htdocs中\ directory5.php在線路32

嚴格的標準:只有變量應該通過引用 C下通過:\ XAMPP \ htdocs中\ directory5.php在線路34上

下面是代碼的摘錄:

else 
    { 
    // the extension is after the last "." 
    $extension = strtolower(array_pop(explode(".", $value))); //Line 32 

    // the file name is before the last "." 
    $fileName = array_shift(explode(".", $value)); //Line 34 

    // continue to next item if not one of the desired file types 
    if(!in_array("*", $fileTypes) && !in_array($extension, $fileTypes)) continue; 

    // add the list item 
    $results[] = "<li class=\"file $extension\"><a href=\"".str_replace("\\", "/",  $directory)."/$value\">".$displayName($fileName, $extension)."</a></li>\n"; 
    } 

回答

52

這應該是行

$value = explode(".", $value); 
    $extension = strtolower(array_pop($value)); //Line 32 
    // the file name is before the last "." 
    $fileName = array_shift($value); //Line 34 
+7

所以它真的就像是把事物之外的東西簡單......可以這麼說:對 – 2014-02-27 23:10:05

+0

@JamieHutber好看多了,是的。我可以確認解決方案建議在PHP 5.3.27上運行。 – crmpicco 2014-05-15 10:47:42

+7

@JamieHutber稍微牽涉一點。array_pop的原型是 mixed array_pop(array&$ array) 請注意參數中的&符號。這意味着數組輸入參數通過引用而不是按值傳遞。輸入數組縮短了一個元素,即返回的元素,這是數組中的最後一個元素,它將從輸入數組中移除。修改輸入參數值的唯一方法是通過引用傳遞它。原始代碼的表達式不能修改其值,因爲它沒有具有可引用值的命名內存位置。 – Jim 2015-04-10 18:15:42

24

array_shift唯一的參數是通過引用傳遞的數組。 explode(".", $value)的返回值沒有任何參考。因此錯誤。

您應該首先將返回值存儲到變量中。

$arr = explode(".", $value); 
    $extension = strtolower(array_pop($arr)); 
    $fileName = array_shift($arr); 

PHP.net

下面的東西都可以通過引用傳遞:

- Variables, i.e. foo($a) 
- New statements, i.e. foo(new foobar()) 
- [References returned from functions][2] 

沒有其他的表情應該通過引用傳遞,作爲結果未定義。例如,以下引用傳遞示例無效:

+0

謝謝shiplu ... – user1184100 2012-03-24 01:28:50

3

我有類似的問題。

我想問題是,當你試圖包含兩個或更多的函數處理數組類型的變量時,PHP將返回一個錯誤。

比方說這個。

$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose'); 

// This function returns the last key of an array (in this case it's $data) 
$lastKey = array_pop(array_keys($data)); 

// Output is "key3" which is the last array. 
// But php will return 「Strict Standards: Only variables should 
// be passed by reference」 error. 
// So, In order to solve this one... is that you try to cut 
// down the process one by one like this. 

$data1 = array_keys($data); 
$lastkey = array_pop($data1); 

echo $lastkey; 

你走了!

+0

你是對的。事實上,這些事情確實會造成錯誤和警告。 – 2017-12-24 17:34:06

2

,而不是分析它的手動,最好使用pathinfo功能:

$path_parts = pathinfo($value); 
$extension = strtolower($path_parts['extension']); 
$fileName = $path_parts['filename']; 
相關問題