Home > Software design >  why can't I access a protected method from a private method if the protected ones are inherited
why can't I access a protected method from a private method if the protected ones are inherited

Time:01-21

I do not understand this particular case or what Alexander says.

class instance is not the same as class?

As already Alexander Larikov said that you can't access protected methods from class instance but not only protected methods but also you can't access private methods from class instance. To access a protected method of a parent class from the instance of a subclass you declare a public method in the subclass and then call the protected method of the parent class from the public method of the subclass, i.e.

ALEXANDERS'S SOLUTION:

class testgiver{
    protected function dbConnect($userconnecttype)
    {
        echo "dbConnect called with the argument ".$userconnecttype ."!";
    }
}

class testprinter extends testgiver
{
    // WHAAAAAT? WHYYYYY?
    public function buildquestionarray() // public instead of private so you can call it from the class instance
    {
        $this->dbConnect('read');
   }
}

$tp=new testprinter();
$tp->buildquestionarray(); // output: dbConnect called with the argument read!

'Fatal error call to private method' but method is protected

why can't I access a protected method from a private method if the protected ones are inherited by the subclasses?

CODE BEFORE SOLUTION:

Line 726 of testprinter in the code below:

private function buildquestionarray()
{
  $query = "etc etc";
  **$conn = $this->dbConnect('read');
  $result = $conn->query($query);
  ...

Testprinter extends testgiver. Here's the extension of the class:

require_once('testgiver.php');

class testprinter extends testgiver
{...

And the declaration of the method in testgiver:

protected function dbConnect($userconnecttype)
{...

CodePudding user response:

They didn't really explain it clearly in the other answers.

Visibility of properties and methods (which I'll refer to collectively as "names") is controlled by where the code that tries to access the name is running. It can be in top-level code, a regular function, or a class method. If it's in a method, what matters is the class where the method is defined.

It's not based on the class of the instance that the name is accessed through.

  • If the name is declared private, you can only use the name in a method of the class that declares the name.
  • If the name is declared protected, you can refer to it in a method of that class, and also a method of a parent or descendant class.
  • If the name is declared public (the default, which also applies if the property is added dynamically), you can refer to it from anywhere.
  • Related