Jump to content

Using variables inside an included file, OOP related.


play_

Recommended Posts

Hello. Trying to learn MVC better by creating my own little framework to understand how it works.

 

Things were going OK til now.

 

I have a base class:

<?php

/**
* Base class most classes will extend from.
* Simply put, this class just has methods that
* most, if not all, classes will need.
*/

class Application {

public function includer($path) {

	if (is_readable($path) == true) {
		include_once($path);			
	} else {
		die("404 not found =[");
	}
}




}
?>

 

 

So the above method 'includer' just sees if a file exists/is readable and if so, include it.

 

Here's where I am using said method.

 

class Index extends Application {

function __construct($method = 'view') {
	// load the index model
	include(ROOT . '/app/models/model.index.php');

	// Invoke requested method.
	$this->$method();
}

public function view() {

	$name = 'Smith';
	$this->includer(ROOT . '/app/views/view.index.php');	# Problem here, i think
}


}

 

view.index.php just contains

<?php echo $name; ?>

 

 

All that is called from the index page, with this line of code

Application::includer($controller_path);

 

 

Now, in line

$this->includer(ROOT . '/app/views/view.index.php');	# Problem here, i think

 

If i get rid of $this->includer, the script will work and say 'Smith'.

 

If i have $this->includer(...) or parent::includer(...), it doesn't work.

 

why?

$name is local to the view function and you are including the view file in a separate function.  There are multiple ways to do this, but what comes to mind are the following:  You either need to pass the vars to the includer function (maybe as an array) and then extract() them there.  Or better, at some point set a class var $this->data or something and use that when you need it.

 

I'll give this some more thought after lunch :)

I would probably move the view() method into the Application class or build a View class and have it extract the view vars that would either be set in the controller using $this->view_vars or a method of the View class set_vars() or something similar.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.