0

This is how I manage content on my site:

PageLoader.class

class PageLoader {

        private $page_dir;
        private $page_headers = '';
        private $page_html = '';

        public function __construct($page_dir)
        {
            $this->page_dir = $page_dir;
        }

        public function load()
        {
            $file_found = false;

            ob_start();
            $file_found = include("./{$this->page_dir}");
            $file_contents = ob_get_contents();
            ob_end_clean();

            if($file_found != false)
            {
                $this->page_html = $file_contents;
            }
        }

        public function outputBody()
        {
            echo $this->page_html;
        }
    }

index.php

$connection = mysql_connect(....);
$is_user_logged = login(...);


$view = new PageLoader($_GET['page']);
$view->load();

?>
<html>
<head>
<? $view->outputHeaders(); ?>
</head>

<body>
<? $view->outputBody(); ?>
</body>
</html>

One problem with this:

Those two variables $connection and $is_user_logged_in are not accessible from within load() method. Most of my inner pages depend on those variables for various reasons. Since they both appear NULL in that scope, inner pages fail to function.

This could solve the problem: $view->setVariable("connection", $connection) but I have a lot more than 2 'main' variables so I'm not sure if this is the best way...

What can I do? Feel free to suggest any alternative ways for me to manage my content as my way is probably the least professional...

Athlon1600
  • 73
  • 3
  • 8
  • Very closely related: [In a PHP project, how do you store, access and organize your helper objects?](http://stackoverflow.com/q/1812472) – Pekka Sep 24 '11 at 18:15

1 Answers1

0

The immediate answer to your question is: Import global variables. In php global variables have to be explicitly "imported". This is done with the global keyword:

$gvar = "asdfad";
function myfunction()
{
    global $gvar;
    echo $gvar;
}

This however doesn't seem as the best idea, because this means that your class is not a logical independent unit.

You probably should declare properties in the class (that hold the required data) and are set at some external initialization (like a constructor).

Willy
  • 167
  • 3
  • 5