Jump to content

Question about access modifiers in OOP


eldan88

Recommended Posts

Hello,

 

I starting learning OOP, and I love it! I was playing around with access modifiers and came across something I had difficulty understanding.

 

On The code below i set the function protected1() to be protected. Which is supposed to be accessed from the class or subclass

 

so I created a subclass called example2 that extends example. Then i set $example1 to instantiated sub class example2 and called protected1() function, and it did not call work?

 

Why is that?

 

 

class Example {
public function public1() { // Everywhere
echo "This is Public";   
}
private function private1() { // This class only
echo "This is private";
}
protected function protected1() { // this and the subclasses only
echo "This is protected";
  }
}
class example2 extends example {

}

$example1 = new example2();
echo $example1->protected1();

Link to comment
https://forums.phpfreaks.com/topic/273166-question-about-access-modifiers-in-oop/
Share on other sites

The sub class has access, true. You cannot try to access it as a method of said subclass, though.

 

Try this:

 

 

class example2 extends example {

public function getProtected1(){

parent::protected1();

}

}

 

$example1 = new example2();

echo $example1->getProtected1();

class example2 extends example {
    public function getProtected1(){
        parent::protected1();
    }
}




$example1 = new example2();
$example1->getProtected1(); 

 

Also, you don't need to echo the method call, because it's echoing inside of your class definition already.

Why is that?

 

Quick rundown of the modifiers:

 

public means the member is visible to all scopes of the current class or any sub-classes of it.

protected means the member is visible to only the class scope of the current class or any sub-classes of it.

private means the member is visible to only the class scope of the current class.

 

By class scope I mean from within the class definition code.  Ie:


class ABC {
  protected function myMethod(){
     echo 'Hello';
  }

  public function someOtherMethod(){
     $this->myMethod();  //You can access the method here.
     echo ' World!';
  }
}

$a = new ABC();
$a->myMethod(); //But not here
$a->someOtherMethod(); //It can be called indirectly through a public method.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.