Screencast: PHP Objects & Classes - Part II
The second part of our Objects & Classes series covers a bit more of the basics. We discuss member-visibility, and how to lock-down specific variables (properties) within classes. We also look at the __construct(), and __destruct() functions (methods), and how they can be used. Lastly, we check out PHP5’s instanceof abilities, to test the types of objects, and what may or may not be in their history of inheritance! Show Notes:
- __construct() and __desctruct()__construct() is the constructor function(Method). It is ran whenever a new instance of a class is created. Often times, it is used for opening database connections, setting character defaults in video games, and many other start-up processes.__descruct() is called whenever a script is finishing, or when an object becomes unset, by the unset() function. It is usually used to clean up, like closing database connections, etc.
- Member-Visibility (Public, Protected, and Private)public means the member is visible everywhere! Be careful how you use this, somethings are best left to protected or private status.protected means the member is only visible to the class that holds it, or any classes that extend from the class the holds it.private is the ultra-lock-down. It is invisible to everybody, and everything, that isn’t the class that contains it. So declaring a member with private means nobody, not even extending classes, will be able to access it directly.Accessing protected or private members from ‘outside’ areas is still possible, if the person who designed the class allows it. If a private member needs to be accessed from within a class, you would call a corresponding function that will retrieve it for you.As an example, when you used to go to your friends house as a youngster, you would ask his mother, “Hey Mrs. Randolph, can billy come out to play?” You would ask her, because billy is somewhere in a house that you aren’t allowed to just walk into at any time, so you ask motherOfBilly() method to go and get billy for you. She then brings him to the front door and serves up the protected member!
- instanceof and TypesPHP5 brought along a neat little tool, called instanceof. This is basically used for testing the type of an object. What I mean by that is, if you have a class called Animal, and a class that extends Animal called Dog, and an object called Rufus who is an instance of class Dog, you could test to see if Rufus is an Animal. Why would you want to do that? Maybe Rufus is a cat, and not a dog (strange name for a cat, huh!). The point is, when you’re dealing with alot of extending, and a lot of classes, instanceof is very useful.