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
Share on other sites

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.

Edited by The Letter E
Link to comment
Share on other sites

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.

Edited by kicken
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.