PHP OOP Concept - Object Basics

This note is taken when reading “PHP Objects, Patterns and Practice, 2nd edition - “

- A wonderful relationship between Class and Object

- A class is the core template used to generate objects (an object’s blueprint)

- An object is data that has been structured according to the template defined in class (an instance of class)

- A property is a member variable in class, holds data that can vary from object to object. As a rule of thumb, it is not possible to access data defined in a scope that is more local than the current.

- Method is a special function declared within a class.

- Using public, protected, private to define the scope of property and method

- The contructor method is invoked when an object is created, it ensure all essential properties of the object is set.

- Predictability is an important aspect of OOP: essential properties must be set when object is created; variables are validated in correct type; correct arguments in method (‘type hint’ - put class name before argument, ex: public method(ClassName $object){}; supporting array type hint, and null default value in hinted arguments   )

- You should have two class, one for managing, one for writing (ex: class ShopProduct & class ShopProductWriter) to seperate the job.

- Key difference between type and class: when u define a class -> u define a type, but a type can be describe an entire family of classes. This mechanism by which differenct classes can be grouped together under a type is called inheristance

- Inheritance is a mechanism by which one or more class can be derived from a base class.(subclass (children) «derived» superclass (parent) )

- The child classes inherit access to all the parent’s public and protected methods (though not to privates methods and properties) So we can treat a subclass’s object as if it was a superclass method (such as: call a superclass’s method from a subclass’s object)

- Derived class can extend but also alter the functionality of their parent.

- As a rule of thumb, you should avoid giving parent classes any special knowledge of their children.

- Public properties and methods can be accessed from any context

- A private method or property can only be accessed from within the enclosing class. Even subclasses have no access.

- A protected method or property can only be accessed from within either the enclosing class or from a subclass. No external code is granted access.

- It’s a good idea to deny direct access to properties, providing methods instead relay needed values. Such methods are accessors or getters and setters. You can use an accessor to filter a property value according to circumstances (ex: change ‘price’ value with or without ‘discount’ according to each ‘product’). You can use a setter method  to enforce a property type.

This was posted 2 years ago. It has 0 notes.