66h3m3ab
66h3m3ab

Reputation: 1148

Overriding parent function

This is a question that's been asked a lot of times, but none of the answers seem to apply here.

I have the following PageBase class:

<?php
    class PageBase {
        public $templatefile = '404';

        function Before() {}
        function After() {}

        function Display() {
            $smarty = System::GetSmarty();
            $smarty->display('views/'.$this->templatefile.'.tpl');
        }

        function Run() {
            self::Before();
            self::Display();
            self::After();
        }
    }

All this class is meant to do is offer a base for my other pages; these pages may or not need to have their own code ran before/after displaying the page and they usually have their own $templatefile. For example my Home class;

<?php
    class Home extends PageBase {
        public $templatefile = 'home';

        function Before() {
            var_dump($_REQUEST);
        }
        function After() {}
    }

The issue I'm running into is that the correct template file (home) is loaded, but the code in Home::Before() is not ran through the instantiated $home->Before(), PageBase::Before() is ran instead.

What is the correct way to tackle this? Does PHP offer any way to override the parent's functions at all?

Kind regards

Upvotes: 0

Views: 1898

Answers (1)

huzi8t9
huzi8t9

Reputation: 292

Personally, I would use an interface for uniformity and call the parent once variables have been set, like so:

    <?php
Interface PageBase {
    public function Before();
    public function After();
    public function Display();
    public function Run();
}

class Page Implements PageBase {
    public $templatefile = '404';

    function Before() {}
    function After() {}

    public function Set($page) {
        if (class_exists($page)) {
            $class = new $page($page);
            return $class;
        }

        return false;
    }

    function Display()
    {
        $smarty = System::GetSmarty();
        $smarty->display('views/' . $this->templatefile . '.tpl');
    }

    function Run()
    {
        self::Before();
        self::Display();
        self::After();
    }
}

class Home extends Page Implements PageBase
{
    public $templatefile = 'home';

    function After() { parent::After(); }
    function Display() { parent::Display(); }
    function Run() { parent::Run(); }

    function Before() {
        var_dump($_SERVER);
    }
}

$Page = new Page(); //Create a new page instance for all of the functionality
$home = $Page->Set("Home"); //Returns a new class of Home
$home->Display(); //Displays the templatefile "home"

I hope this helps.

Upvotes: 1

Related Questions