HTML and CSS Reference
In-Depth Information
Starting at the top, this class defines two properties: $view , which stores the name of the view to be loaded; and
$vars , which is an array of view-specific key-value pairs to be used for customizing the output.
The __construct() method checks for a view slug or string identifying the view, and stores it in the object for
later use, or it throws an Exception if none is supplied.
The __set() method is another magic method (which we'll talk more about in the next section) like __construct()
that allows the storage of data in an object as properties, even when the properties are not explicitly defined.
This creates a shortcut for adding variables for output in the views.
Finally, the render() function uses the extract() function to store all the custom properties into variables,
checks for a valid view file, and either prints or returns the markup for the view based on the $print flag.
WhY SetterS are USeFUL
like all the other magic methods in php, the __set() method is not actually that magical; it simply provides a
shortcut for doing something that would otherwise be cumbersome.
For example, our various views will not share the same variables for output: a room will have a title and presenter,
whereas the question view will have the question text and number of votes.
While you could explicitly declare each property in their respective views, that adds a maintenance headache if
additional properties are added in the future.
alternatively, you might use a dedicated property to hold an array of custom variables for each view:
<?php
class RWA_Example
{
public $vars = array();
}
$test = new RWA_Example;
// Sets custom variables
$test->vars['foo'] = 'bar';
$test->vars['bat'] = 'baz';
// Gets custom variables
echo $test->vars['foo'];
echo $test->vars['bat'];
this is a perfectly acceptable solution, but it's a little unwieldy to type.
using the magic setter method simplifies this process by providing a shortcut: simply set the properties as if they
were explicitly declared, then use __set() to put them in an array.
to retrieve the custom variables, there's another magic method called __get() .
 
Search WWH ::




Custom Search