Class does not extend from another

-1

Hello, I'm having trouble using extends in a certain class , see my code below:

Template class:

<?php

class Template {
    private $_strings = array();
    private $_template;

    public function set($file) {
        $path = 'templates/' . DEFAULT_THEME . '/' . $file . '.tpl.php';

        if (!empty($path)) {
            if (file_exists($path)) {
                $this->_template = file_get_contents($path);
            } else {
                die("<b>Template error: </b> arquivo não encontrado: <i>{$file}.tpl.php</i>");
            }
        }
    }

    public function assign($string, $toReplace) {
        if (!empty($string)) {
            $this->_strings[$string] = $toReplace;
        }
    }

    public function show() {
        if (count($this->_strings) > 0) {
            foreach ($this->_strings as $key => $value) {
                $this->_template = str_replace('{' . $key . '}', $value, $this->_template);
            }
        }

        return $this->_template;
    }
}

Class using extends

class Spinxo extends Template {

    public function __construct() {
        $tpl = new Template;
    }

    public function load() {
        global $tpl;
        $tpl->assign('web_title', 'titulo do site');
    }
}

What I want, I want this class Spinxo to load all the settings, this is my home:

$tpl = new Template();
$spx = new Spinxo($tpl);

$url = (isset($_GET['url'])) ? $_GET['url'] : 'home';

switch ($url) {
    case 'home':
        $tpl->set('home');
        $spx->load();
        break;
}


echo $tpl->show();

As you can see I'm instantiating my object with the variable $tpl when I take the extends of my Spinxo class and use global $tpl it works ... I do not know if I can explain it, but whoever understands please respond. : D

    
asked by anonymous 24.02.2016 / 04:17

2 answers

1

You are mistakenly implementing your child class. I do not understand the purpose of the template class, but for what you want to do, this is enough:

class Spinxo extends Template {

    public function load() {
        $this->assign('web_title', 'titulo do site');
    }
} 

Spinxo already has method assign inherited from Template . At the time of using the class you also do not need to pass Template as a dependency of Spinxo :

$spx = new Spinxo();

$url = (isset($_GET['url'])) ? $_GET['url'] : 'home';

switch ($url) {
    case 'home':
        $spx->set('home');
        $spx->load();
        break;
}


echo $spx->show();
    
24.02.2016 / 04:28
-2

Put a require_once in the code where you give extends

<?php

require_once("template.class.php");

class Spinxo extends Template {

    public function __construct() {
        $tpl = new Template;
    }

    public function load() {
        global $tpl;
        $tpl->assign('web_title', 'titulo do site');
    }
}
    
24.02.2016 / 04:19