1

I don't completely understand this line of render.

function render($view, $values = [])

I know it passes two arguments, the second is an empty array that you can fill I think?

I used this in 'Quote':

render("quote_view.php", ["title" => "Quote", "STOCK" => $stock]);

$stock is an associative array containing name, symbol and price.

The parts I don't understand are:

  • why "=>" is used instead of "="
  • I don't understand the relationship between STOCK and $stock.

I got it working but I am just trying to understand it. Thanks.

1 Answer 1

1

=> is the notation for a key-value pair in an associative array.

Arrays that are indexed by key-value pairs like this (instead of indexed by integers, like arrays in C) are sometimes called "hashes" (because they are data structures analogous to "hash tables" in C), so you may sometimes hear => referred to as a "hash rocket".

The render() function needs a "hash rocket" in its arguments for a quite interesting reason.

Let's look in helpers.php:

/**
 * Renders view, passing in values.
 */
function render($view, $values = [])
{
    // if view exists, render it
    if (file_exists("../views/{$view}"))
    {
        // extract variables into local scope
        extract($values);

        // render view (between header and footer)
        require("../views/header.php");
        require("../views/{$view}");
        require("../views/footer.php");
        exit;
    }

    // else err
    else
    {
        trigger_error("Invalid view: {$view}", E_USER_ERROR);
    }
}

Two arguments are passed to render(). The first is $view, which is a View (or PHP template) similar to header.php and footer.php. Only one View is passed to render(), so this variable is a scalar value; that is, a variable which holds only one value at a time.

But when we want to include dynamic data from our Controller inside a View template, we don't know how many values we will need in advance. We need a way to pass an arbitrary number of values out of the Controller's local scope and into the View's scope. A scalar value won't do. We need a hash.

The key to this whole business is right here:

    // extract variables into local scope
    extract($values);

Read up on extract() for the details. Each key-value pair in the associative array creates a local variable in the View's symbol table, treating keys as variable names and values as variable values.

Hope this helps.

1
  • 1
    Explained perfectly I understand it now thanks! Sep 21, 2016 at 10:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .