I am learning about OO and classes, I have a couple of questions about OO and classes in PHP
As I understand it, a class that extends another class simply means that the class that extends the other class has access to the variables/properties and the functions/methods of the class that it is extending from. Is this correct?
I know that a static method or property are basically the same as a procedural function or variable outside of a class and can be used pretty much anywhere. Is this correct?
Public means any class can access it and Private means only the class that is is encapsulated in or a class that is extended from the owner of can access and use. Is this correct?
1) Yes, that's correct. A child class inherits any
protected
orpublic
properties and methods of its parent. Anything declaredprivate
can not be used.2) This is true. As long as the class is loaded (this goes well with your autoloading question from before), you can access static methods via the scope resolution operator (::), like this:
ClassName::methodName();
3) You have the meaning of
public
correct, but as I mentioned earlier,private
methods can only be used by the class they are declared in.The above code will result in a
NOTICE
error being triggered, as $x is not accessible by childClass.If $x was declared
protected
instead, thenchildClass
would have access. Edit: A property declared asprotected
is accessible by the class that declares it and by any child classes that extend it, but not to the "outside world" otherwise. It's a nice intermediate betweenpublic
andprivate
.There's very little need to declare anything private, as a general rule use protected instead.
For 1. As I understand it, a class that extends another class simply means that the class that extends the other class has access to the variables/properties and the functions/methods of the class that it is extending from. Is this correct?
ANS: That is correct but that is not all. The extending class can also customize the extended class by overriding the method of the extended class. And ofcouse, it can also extend the super class functionality by adding new fields and methods.
For 2. I know that a static method or property are basically the same as a procedural function or variable outside of a class and can be used pretty much anywhere. Is this correct?
ANS: Yes that is correct and as zombat said as long as the class is public and loaded and the property and method is public. In other word, you are using the class as name space of those elements.
For 3. Public means any class can access it and Private means only the class that is is encapsulated in or a class that is extended from the owner of can access and use. Is this correct?
ANS: Think of it as physical properties, public computer (at a library) can be used by everyone and your private computer (supposibly) can only be used by you.
Just to added to Zambat comment.