I am trying to create a PHP MVC App which has a file structure like this
in init.php
I have
<?php
include('app/Database.php');
include('app/models/m_template.php');
include('app/models/m_categories.php');
$Database = new Database();
$Template = new Template();
$Categories = new Categories($Database);
in m_tenplate.php
I have Template()
class like this to load files.
class Template
{
function __construct() {}
public function load($url, $title = '')
{
if ($title != '') { $this->set_data('page_title', $title); }
include($url);
}
and in m_vcategories.php I have Categoty() class like
class Categories {
function __construct() {}
public function test(){
echo 'This is Test';
}
in index.php I have
<?php
include 'app/init.php';
$Template->load('app/views/v_home.php');
now when I try to access the Categories() methods through v_home.php
in Views like:
<?php
$Categories->test();
I am getting following errors
can you please let me know why this is happening?
$Categories
is outside of the load
methods scope, which also means it is out of scope for any files included within the load
methods body.
Here is a solution which you could use to work around this:
// Add a $variables parameter to your load method.
public function load($url, $title = '', $variables=NULL)
{
if( is_array($variables) )
{
foreach( $variables as $key => $item )
{
$$key = $item;
}
}
if ($title != '') { $this->set_data('page_title', $title); }
include($url);
}
Then you use the load method like this:
<?php
include 'app/init.php';
$Template->load('app/views/v_home.php', '', array('Categories' => $Categories);
You put an associative array of items you would like to make available to the template page.
The variable categories isn't available at v_home scope, to achieve this you need to add new parameter to your Template class - in load method and extract the contents of that variable, it will be like this
public function load($url, $title = '',$data = array())
{
extract($data);
if ($title != '') { $this->set_data('page_title', $title); }
include($url);
}
http://php.net/manual/en/function.extract.php
then in index.php you can do this
<?php
include 'app/init.php';
$Template->load('app/views/v_home.php','',array('Categories' => $Categories));
or
<?php
include 'app/init.php';
$Template->load('app/views/v_home.php','',compact('Categories'));