views:

54

answers:

3

Here is the code:

Class_view.php contains the class definition as an associative array:

class View {
    private $viewArray=array(); 
    function getViewArray() {
        return $this->viewArray;
    }
    function addToViewArray($key,$value){
        $this->view[$key]=$value;
    }
}

In Index.php I have:

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

And the code that causes the error is in UI_Header.php, arount the "title" HTML tags:

<?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"&gt;
<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>

I'm trying to get the value associated with the key 'title' to show here.

The error I get is:

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

Thank you,

JDelage

+4  A: 

The problem is $view->getViewArray()['title']. PHP doesn't support this yet (it will be included in the next PHP version.) For now you need to create a temporary variable:

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

(But maybe you shouldn't put that in one line, it's hard to read. Maybe put a $viewData = $view->getViewArray() at the top of that script ;)

Another way (which is way more elegant) is to implement the ArrayAccess interface in the class, so you could directly use $view['title']. Or, alternatively, if you prefer using object access over array access you could implement the magic __get method (and __set, __unset and __isset methods, if you need them.)

nikic
Thank you. The ArrayAccess interface is way over my head - I couldn't follow the manual's explanations. Maybe in a few months...
JDelage
@JDelage: Simply copy the four methods (the ones starting with `offset`) into your `View` class and replace all occurances of `$this->container` with `$this->viewArray`. Now you can use an instance of the class (`$view = new View;`) like an array. So to set the title you use `$view['title'] = 'Some nice title';` instead of `$view->addToViewArray('title', 'Some nice title')` and to get the title you use `echo $view['title'];` ;)
nikic
A: 

change $this->view[$key]=$value to $this->viewArray[$key]=$value

Alexander.Plutov
Though that might be a good idea, that's certainly not going to cause a parse error.
zneak
+1  A: 

In PHP, the array subscript syntax can only be used on a variable. You can't do $view->getViewArray()['title']. You need to assign the result of $view->getViewArray() to a variable, then do $variable['title'].

zneak
This is good to know, thanks.
JDelage