PHP with MySQL Beoyond the Basics
Chapter 4: OOP in Practice
This chapter continues with the basics of object-oriented programming.
Exericses
- Understanding Class Inheritance
- The page displays the properties of two classes,
Car
andCompactCar
. Their properties are the same becauseCompactCar
extendsCar
. - Setting Access Modifiers
- This exercise covers using the Public, Private, and Protected keywords. Items with Public access can be called from anywhere, this is the default access type; items with Private access can only be called within the class; items with protected access can be called by the class and any of its subclasses.
- Using Setters and Getters
- The exercise covers making setter and getter methods.
- Working with the Static Modifier
- The
static
keyword allows the item to exist even if there is no instance of the class. The page displays the information in the class using theClass::attribute
syntax. With static methods, you can't use$this
, so you have to use the double-dot notation plus a dollar sign. Static methods are shared throughout the inheritance tree. Defined once, called everwhere. - Referencing the Parent Class
- Use
self::
to reference the same class;ClassName::
to specify a parent;parent::
to use the parent without its name. The page displays various ways of using references to the parent class. - Using Constructors and Destructors
- Constructors are used to perform functions when the class is first created. Destructors are used to perform functions as the class is being destroyed. The page displays some basic data that's been created through the
__constructor
method. - Cloning Objects
- The exercise covers creating references to objects vs. cloning objects. It also covers using the
__clone
method. - Comparing Objects
- The exercise displays the way to use comparison operators and identity operators. The comparison operator will return true in comparing objects that are references and between instances with matting references. The identiy operator will return true only between references. Both return false when comparing instances with different attributes.