0

I have a problem with objects in PHP.

http://codepad.org/HdqCVJlw

<?php
error_reporting( E_ALL | E_STRICT );
##
class Loader {
    function view() {
        echo 'I did it! )';
    }
}
class Controller {
    public $loader;
    function __construct() {
        $this -> loader = new Loader;
    }
}

##
class Foo extends Controller {
    function index() {
        $this -> loader -> view();
    }
}

There are three classes: Loader, Controller and Foo. I want to use method of class Loader in Foo class. I know that __construct() wouldn't run because Foo extends from Controller, but anyway I don't get any error.

So how to use that method there with condition that in Foo I won't need to write more code?

P.S. I'm creating MVC...

2
  • I don't understand your problem. Your code is working here... Commented Mar 1, 2011 at 13:05
  • (sidenote) Ask yourself if your Controller really is a specialized Loader. If the answer to that is No, then Controller should not inherit from Loader. If Controller just uses a Loader, then you should favor Composition/Aggregation over Inheritance. Commented Mar 1, 2011 at 13:17

2 Answers 2

4

I know that __construct() wouldn't run because Foo extends from Controller, but anyway I don't get any error.

When instantiating Foo, Controller's __construct() will be run.

The exception is if you make a __construct() within Foo, and forget to call parent::__construct().

The code you posted works fine.

Sign up to request clarification or add additional context in comments.

Comments

0

Add a constructor to Foo that calls parent::__construct();.

http://php.net/manual/en/language.oop5.decon.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.