Visibility in PHP

Josh Sherman
1 min read
Software Development PHP

Visibility of functions and properties is very important when you are attempting to lock down certain aspects of an object. In PHP there are three levels of visibility, public, private and protected. Let’s take a look at what each one means.

Public

Public is the easy one. It’s the default visibility and it means any and everyone has access to it. If you come from Python land, it’s all you know because Python doesn’t have anything else because “we’re all consenting adults”.

I tend to agree with this sentiment because it gets very tiresome trying to protect developers from themselves. Public visibility on properties in PHP allows you to get and set variables without any getter or setter methods. Definitely a win.

Protected

Protected properties and functions are accessible from the class itself as well as any derived classes. This is great when you want to have classes inherit from another class and you want shared access. Other objects would not have access to these entities as if they were public.

Private

The most restrictive of the bunch, private properties and functions are only accessible by the defining class itself. This is great when you only plan to use the entity in the class itself and will not bt extending it at all. Pairs well with the final keyword.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles