English Subtitles for PHP Object Oriented Programming (OOP): Visibility (5/13)



Subtitles / Closed Captions - English

So by now, if you haven't already, you're probably going to be wondering what this means. We've always used public. But there's actually three scopes of visibilities in total. Let's list them up here.

We have public. We have protected. And we have private. And I'm going to demonstrate each of these to you. So let's start with these. I'm going to change these to protected.

And inside our penguin class, I'm just going to create a new method. And I'm just going to call this foo, since this is just a test. And what I'm going to do is I'm going to echo this legCount. So I'm referring to this property.

And like I said in the last tutorial, every subclass, i.e. a class that inherits another class, inherits all of its properties. So this should work fine. So check-- we didn't call the method. Penguin foo.

And we get 2, which is fine. That's expected. However, if we were to change this to private, we get undefined property penguin And that's because when we set a property or method's visibility

to private, only the class that it's in can access them. So you see down here, we're returning this That's fine, because this method is in this class. But here, we're getting an error, because this penguin class is a totally separate class, even though it's a subclass.

Now, protected means that subclasses-- i.e. Classes that inherit the class-- they can access them. So this will be fine. However, if we try to access this property from outside of the class-- so penguin legCount, we get, cannot access protected property penguin legCount.

However, if we change this to public, hit refresh-- and I didn't echo it-- we get 2, which is great. And this also works with methods. So if we change this to private, and we say, if penguin canFly, and we'll just do something here. Hit refresh and we get, call to private method bird canFly.

And the same with protected. Call to protected method bird canFly. So we have to keep this at public to allow our developers to use this outside of the subclass. And that's why we use getters and setters as well.

So we can access the properties that are set to protected and private without having an issue.



Video Description

Want more? Explore the library at https://www.codecourse.com/lessons

Official site
https://www.codecourse.com

Twitter
https://twitter.com/teamcodecourse