0

I keep an abstract class definition in a directory called /classes. It looks like this:

abstract class baseController { protected $registry; //Obtain registry object protected function __construct($reg) { $this->registry = $reg; } protected function show() { } } 

In the /controllers/ directory (they share the same parent folder) I have my specific controller class files. For instance,

class indexController extends baseController { public function show() { //render index page $this->registry->view->render('index'); } 

}

I use two spl_autoload_register() calls in my config script to make sure that both directories are found when classes are needed - but when I try to instantiate indexController from my router.class.php file (which is in the /classes/ directory) I get the following error:

PHP Fatal error: Call to protected baseController::__construct() from context 'router'... 

It's identifying the line: $this->controller = new indexController($this->registry); as the culprit.

The __construct is protected, but indexController should be inheriting from baseController and therefore, since the __construct method isn't redefined, it should be calling the parent classes constructor. Or so I thought.

What the heck is going on?

1 Answer 1

3

You should use public definition in __construct method, since you instantiate the class outside the class context (ex in Router class).

This may work if you instantiate it inside another class that extends baseController.

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

5 Comments

So, if I'm instantiating a class that extends a base class in the context of a third (unrelated) class, then I need to define the constructor method as public? I don't understand why that would be an issue, since the object I'm creating is still an extended version of the abstract class.
This worked, but I would love an explanation about why the child class was "out of context" in this case?
Imagine that when you call new indexController() it is like a shortcut of calling __construct() method for this class. So like other methods in classes it must be public if you call it outside of class context.
OH - I think I just got it. Even if indexController didn't extend another class, I couldn't instantiate it in a normal block of code because the __construct() method is protected, not public! Am I right?
Yes that 's right. If the __construct method is not public you cannot instatiate the class outside the class context.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.