mardi 7 mars 2017

Get variable from index.php instead of the function that parse the template

I'll just start by giving the codes I just wrote then I will show you what I mean:

init.php, this will be required in every PHP page, it's like the base file of all PHP core.

<?php

spl_autoload_register(function ($class) {
    @include_once $class.'.php';
});

try
    $app = new app();
catch(Exception $e)
    die($e->getMessage());

?>

app.php, more like the classes manager, to access any class object you have to do it through here.

<?php

class app
{

    function __construct()
    {
        require_once 'config.php';
        if(!isset($config) || !is_array($config))
            throw new Exception("Couldn't load the Config file.");

        $this->config = $config;

        $this->template = new template($this);
    }
}

?>

config.php, just a test file where I try to access from the template

<?php
    $config['name'] = "Name here";
?>

template.php, template handler

<?php

class template
{
    private $app;

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

    public function ParseTemplate()
    {

        $someVar = "Works";

        // Get the file contents.
        $content = file_get_contents("template.tmp");

        // Check for variables within this template file.
        preg_match_all('/{\$(.*)}/U', $content, $matches);

        // Found matches.
        foreach ($matches[0] as $id => $match) {
            $rep = $matches[1][$id];
            $content = str_replace($match, $$rep, $content);
        }

        // Output the final result.
        echo $content;
    }
}

?>

Basically, that's the core code, everything here is working just fine. Now when I try to use the code like this:

index.php, this is a normal PHP page

<?php

    require_once 'init.php';

    $variable = "This is test.";

    $app->template->ParseTemplate();

?>

Now index.php will require init.php which will set up app and template classes, and so I parse the template to post it:

template.tmp, and finally this is the template.

The result is: {$variable}
Name: {$app->config['name']}
Another variable: {$someVar}

The result I want it to give is

The result is: This is a test. // taken from index.php since $variable is there.
Name: Name here //It will access $app->config and get the name
Another variable: Works // I don't honestly care if this works or not it's just a test.

But the result it gives instead is:

The result is: Notice: Undefined variable: variable in template.php
Name: Notice: Undefined variable: app->config['name'] in template.php
Another variable: Works

So my question is how to make the template "check for" or "get" the variables that are in index.php and not inside the function ParseTemplate itself?

Sorry for the long code and if you didn't understand my question then tell me and I'll try to explain better (I suck at it)

Thanks in advance, much appreciated.




Aucun commentaire:

Enregistrer un commentaire