views:

30

answers:

3

I have a php site which flows as shown below. Please note I'm leaving out most of the code (wherever theres an ellipses).

index.php

include template.php
...
$_template = new template;
$_template->load();
...

template.php

class pal_template {
...
public function load() {
  ...
  include example.php;
  ...
}

example.php

...
global $_template;
$_tempalate->foo();
...

Now, this works fine. However, I end up having a ton of files that are displayed via the $_template->load() method, and within each of these files I'd like to be able to make use of other methods within the template class.

I can call global $_template in every file and then it all works fine, but if possible I'd really like for the object $_template to be available without having to remember to declare it as global.

Can this be done, and what is the best method for doing it?

My goal is to make these files that are loaded through the template class very simple and easy to use, as they may need to be tweaked by folks who basically know nothing about PHP and who would probably forget to put global $_template before trying to use any of the $_template methods. If $_template were already available in example.php my life would be a lot easier.

Thanks!

+2  A: 

You can define globals before you include 'example.php'.

global $_template;
include 'example.php'

Or you could do this:

$_template = $this;
include 'example.php'

Or inside example.php:

$this->foo();
konforce
Exactly, use `$this->foo()`
Sean Huber
Perfect, that takes care of it!!
Andrew
A: 
Yanick Rochon
A: 

I recommend you to not use "global", as Yanick told you as well.

What you probably need is the Registry design pattern. Then you can add the template to the registry and give it to every object. In general I would recommend you to learn about design patterns. Here are some more you could learn.

Raffael Luthiger
If I use the registry pattern, can I make the variable available to whoever else might be editing "example.php" without them having to declare it?
Andrew
Yes. This person has to take this variable out of the registry and then use it. If this person needs to give this variable to some other part of the code then he can put this information/variable back into the registry.
Raffael Luthiger