I'm talking specifically about the public, private and protected keywords that can apply to properties and methods. I've looked everywhere and I know what they do and how to use them, but don't see how they would be practical when programming. Could somebody explain or give an example?
The primary purpose of encapsulation (scope) is to ensure that you write code that can't be broken. This applies to scope in general, so let me use a simpler example of a local variable inside a function:
function xyz ($x) {
$y = 1;
while ($y <= 10) {
$array[] = $y * $x;
$y++;
}
return $array;
}
The purpose of this function is to pass a number and return an array. The example code is pretty basic. In order for function xyz() to be dependable, you need to be guaranteed that it does the exact same thing every time. So what if someone had the ability to from the outside change that initial value of $y or $array? Or even $x? If you were able to do that from outside of the function, you could no longer guarantee what that function is returning.
That is where scope (encapsulation) comes into play. It is a way of setting boundaries, of assigning permissions of what can and can't be done with your variables (and functions, properties, methods, objects) to make sure that bit of code will always do exactly what it is expected to do.
Take for instance any built-in php function like...strtolower() or preg_match() or ...well anything. They expect arguments to be passed to them, and they return something specific. Internally there are variables, loops, etc... to take the input and spit out an output. If you were to be able to change that stuff from the outside, there would be no way to guarantee that strotolower() will return a lowercased string you feed it, and that defeats the purpose of having a reusable code block.
This isn't necessarily all that useful when you are programming for yourself, but when you are writing code to be used and shared by many people, especially with using code that involves addons/plugins, etc... it is invaluable for ensuring your code does what it is supposed to be doing, and is accessed/used/called in an expected way.