Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an "Access Level must be protected or weaker" after extending a protected class variable and marking it private?

abstract class AbstractController
{
    protected $repository;
}

class GraphController extends AbstractController
{
    private $repository;
}

I get this error:

Fatal error: Access level to GraphController::$repository must be protected or weaker

Why? What's the theory behind this? On some level it feels wrong that I could have a weaker access level to a class property (i.e. public) when I extend a class, because I am in a way exposing a variable that was meant by parent class to be more restricted...

like image 681
Dennis Avatar asked Jul 24 '17 21:07

Dennis


1 Answers

It's a rule of the inheritance. You can make the visibility weaker (more visible) of an inherited member, but you can't hide it more. So you can either make it protected, or public. The rationale being you shouldn't be able to hide members from the base class, or make members less visible than the base class author intended. Add to, yes, take away from, no.

like image 172
Fred Woolard Avatar answered Oct 05 '22 02:10

Fred Woolard