2010-09-15 35 views
0

Class_view.php包含類定義爲一個關聯數組:PHP解析錯誤 - 請指出編碼恐怖

class View 
{ 
    private $viewArray = array(); 

    function getViewArray() { 
     return $this->viewArray; 
    } 

    function addToViewArray($key, $value) { 
     $this->view[$key] = $value; 
    } 
} 

的index.php中我有:

$view = new View(); 
$view->addToViewArray("title", "Projet JDelage"); 
// Much more code 
include ("UI_Header.php"); 

而引起的代碼錯誤在UI_Header.php,在「標題」HTML標籤附近:

<?php 
    echo '<?xml version="1.0" encoding="utf-8"?>' 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr"> 
    <head> 
     <title><?php echo htmlspecialchars($view->getViewArray()['title']);?> 
     </title> 
     <link rel="stylesheet" media="screen" type="text/css"  title="StyleSheetProjet" href="StyleSheetProjet.css" /> 
    </head> 

我試試以獲得與此處顯示的密鑰'title'相關聯的值。

我得到的錯誤是:

Parse error: parse error in Header.php on line 7

+0

*(related)* [Array dereferencing](http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html) – Gordon 2010-09-15 15:11:06

回答

4

問題是$view->getViewArray()['title']。 PHP不支持此,但(it will be included in the next PHP version。)現在,你需要創建一個臨時變量:

<?php $data = $view->getViewArray(); echo htmlspecialchars($data['title']); ?> 

(但也許你不應該把在一條線,這是很難讀的話放一個$viewData = $view->getViewArray()在該腳本的頂部;)

另一種方式(這是方式更優雅)是實現班上ArrayAccess接口,所以你可以直接使用$view['title']。或者,如果你喜歡使用了數組訪問對象的訪問,你可以實現神奇的__get方法(和__set__unset__isset方法,如果需要的話)。

+0

謝謝。 ArrayAccess接口在我頭上 - 我無法按照手冊的說明進行操作。也許在幾個月內...... – JDelage 2010-09-15 15:17:11

+0

@JDelage:只需將四個方法(以'offset'開頭的那些方法)複製到'View'類中,並用'$ this->'替換'$ this-> container'的所有出現。 viewArray'。現在,您可以像使用數組一樣使用類的實例('$ view = new View;')。所以要設置你使用'$ view ['title'] ='一些不錯的標題'的標題''而不是'$ view-> addToViewArray('title','一些不錯的標題')'並且得到你使用的標題'echo $ view ['title'];';) – NikiC 2010-09-15 15:45:49

2

在PHP中,數組下標語法只能用在一個變量上。你不能這樣做$view->getViewArray()['title']。您需要將$view->getViewArray()的結果分配給一個變量,然後執行$variable['title']

+0

這很好理解,謝謝。 – JDelage 2010-09-15 15:17:30