Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm new to OOP/PHP. What's the practicality of visibility and extensibility in classes?

I'm obviously brand new to these concepts. I just don't understand why you would limit access to properties or methods. It seems that you would just write the code according to intended results. Why would you create a private method instead of simply not calling that method? Is it for iterative object creation (if I'm stating that correctly), a multiple developer situation (don't mess up other people's work), or just so you don't mess up your own work accidentally?

like image 640
Marc Ripley Avatar asked May 26 '10 14:05

Marc Ripley


People also ask

What is the importance of class visibility in OOP PHP?

Visibility is declared using a visibility keyword to declare what level of visibility a property or method has. The three levels define whether a property or method can be accessed outside of the class, and in classes that extend the class.

What is visibility mode in PHP?

PHP has three visibility keywords - public, private and protected. A class member declared with public keyword is accessible from anywhare. A protected member is accessible from within its class and by inheriting class.

What refers to visibility of methods or properties of a class?

Visibility ¶ The visibility of a property, a method or (as of PHP 7.1. 0) a constant can be defined by prefixing the declaration with the keywords public , protected or private . Class members declared public can be accessed everywhere.


1 Answers

Your last two points are quite accurate - you don't need multiple developers to have your stuff messed with. If you work on a project long enough, you'll realize you've forgotten much of what you did at the beginning.

One of the most important reasons for hiding something is so that you can safely change it later. If a field is public, and several months later you want to change it so that every time the field changes, something else happens, you're in trouble. Because it was public, there's no way to know or remember how many other places accessed that field directly. If it's private, you have a guarantee that it isn't being touched outside of this class. You likely have a public method wrapped around it, and you can easily change the behavior of that method.

In general, more you things make public, the more you have to worry about compatibility with other code.

like image 58
Tesserex Avatar answered Oct 16 '22 11:10

Tesserex