How can I make a regular variable accessible in fi

2019-08-26 02:28发布

问题:

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!

回答1:

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();


回答2:

The use of global is strongly not recommended.

By the way, consider this :

-> index.php

$_template = new template;
$_template->load();

-> template.php

class template {

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

   public function showMessage($file) {
      echo "Message from '{$file}'";
   }
}

-> example.php

<?php

$this->showMessage(__FILE__);

Will output something like

Message from '/path/to/example.php'


回答3:

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.