OBJECT ORIENTED PROGRAMMING IN A NUTSHELL

This post is a brief overview of the fundamentals and principles of Object Oriented Prgramming (OOP).  It is a summary of my notes from an online course in PHP (see end of article for reference), so most of the examples are in PHP, but the principles are universal to OOP.

OOP In a Nutshell:

  • OOP (Object Oriented Programming) refers to a method of programming that works with data which is  grouped into a set called an ‘Object’.   
  • The Object can have properties (stored data) and/or methods (functions that the object can run and call).
  • The Object can be based on a blueprint or parent which defines properties and methods it inherits and has access to and can use (further abstracted and managed by an Interface in some cases).  An example of a blueprint or parent that Objects inherit from would be Classes.

That’s just the tip of the tip of the iceberg.  If your interested in the rest of the tip of the iceberg, then here is some more information:

Definitions:

  • Object: A set of data grouped together by a common theme.  An object could be stored in a variable, function or data structure.  Objects consist of key/value pairs (the key is a placeholder(or representative name) for data, and the value is the actual data stored and associated with the key).
  • Class: Describes the properties and methods of an object (it is like a blueprint or definition of an object). Properties can be variables, arrays, or data;  Methods are functions that create/define behaviors of the object.
  • Property: A key/value pair in an Object that stores descriptive data (for example, an Object holding data about a person could have a property key of ‘name’, which would hold the person’s name as the value).
  • Method: A key/value pair in an Object that stores behavioral data (i.e. a function that does something – for example, modifies some property data, or gets additional data and uses it somehow).  The term ‘Method‘ and ‘Function‘ mean basically the same thing.  When talking about Objects, a ‘Method‘ is basically a function that is stored inside of and can be called from an Object.
  • Instantiation: calling the class with the new keyword to make the properties and methods accessible to an object that is created (by assigning a variable to it).  Example:  $obj = new Class_name();
  • Instance: an object (represented by a variable, for example) that has access to and references  the properties and methods of a parent class.  The instance is created through the process of instantiation (using the new keyword; see above).  In other words, an object is an instance of a class.

Benefits of using OOP (Object Oriented Programming):

  • Enables modular functionality in code.  Complex functionality can be accomplished while simplifying the code and making it cleaner (easier to read and understand).
  • Updating the code or modifying and adding features and functionality is also made easier by using OOP.

CLASSES:

  • To create a Class use the class keyword, then make a name:

Note: The first letter of the name of the class must be CAPITALIZED!

Example (A Class named Car is created and a property and method are assigned to it):

class Car {
//Methods and properties go here;
//Example property:
     var $doors = 4;
//Example method:
     function moveWheels(){
         echo "Wheels are moving!";
     }
}
Other things to note in class creation:
  • When creating a class, create the properties before creating the
    methods.
  • Use the keyword var to create properties (you can assign values or not).
  • You can use method_exists(“methodName”); for debugging if trying to find methods in a lot of code.
Creating properties in the class:
  • Use the keyword var to create properties (you can assign values or not):

Example (the class Car is created with properties and methods defined.  The -> is an access operator that is similar to the . in Javascript):

class Car {
    //(properties created with var)
    var $wheels = 4; 
    var $hood = 1;
    var $engine = 1;
    var $doors = 4;

//Methods(functions) in the class:
//To modify or assign values to properties, use $this variable (refers to the object/class that it is in):

    function changeWheels() {
        $this->wheels = 10; 
        //changes the wheels property value.         
        //Note: you don't use the $ when
        //referencing the properties in this
        //function method to set them.
     }

    function moveWheels(){
        echo "Wheels are moving!";
    }
}

OBJECTS:

To use the properties and methods of a class in an object:

  • Create an instance of the class: use the keyword new followed by class_Name(); i.e. new Car(); <—this creates an ‘instance’ of the class.
  • Assign the instance of the class to a variable – the variable now
    stores the instance of the class and is an object that has access to
    properties and methods of the assigned class.

Example:

$hondaFit = new Car(); 
//this creates an instance of the Car class assigned to $hondaFit (which can be called an object).
To access methods/properties:
  • To access a property/method use the -> operator and the name of the property/method (without the $ included) in PHP.  In Javascript, use the . operator (objectName.property):
Example:
  $hondaFit->wheels;  //returns the value.   
//or 
  echo $hondaFit->wheels; //<--this echoes '4'.

//Example (method access): 
  $hondaFit->moveWheels();

//Modify or assign a value to the object property:
  $hondaFit->wheels = 10; 
//reassigns the value of $wheels to 10.

INHERITANCE:

  • A class can inherit and access the properties and methods of other classes by using the extends keyword:

Example:

class Class_A extends Class_B {

//Class_A now has access to props and methods of      //Class_B.

//Props and methods can be added which Class_A will have in addition to those of Class_B.

//you can override the parent (Class_A) property by using var and assigning a new value to it:
var $propNameFromClass_A = newValue;
}

CONSTRUCTORS:

  • Constructor functions execute every time a new instance is created of the parent class they’re created in (with the new keyword).

Examples of practical use:

  • Create default values when a user is created or some default values of a new object that are automatically created when the object is instantiated.
  •  Automatic validations and site maintenance when new objects are created.

Create a constructor in PHP using function, two
underscores, and construct :

Example:

class Class_A {
    function __construct(){
       //code goes here; this runs every time a new
       //instance of Class_A occurs.
    }
}

DATA ACCESSORS:

Three Types:
  • Public — available to the whole program – scope is global.
  • Protected — only available to the parent class or sub-classes
    (extended) that inherit from the parent.
  •  Private — only available to the parent class (not accessible by
    extended classes).

You can use accessors on methods and properties, as well as classes.

Syntax: put the access type (public protected or private) before the class keyword or variable/property name:

Example:

public class Class_A {
    private $prop1 = value; 
    //only accessible inside the class
}

Uses:
-can be used to hide as much of the inner workings of an object as possible. That way it is less likely to break. 
-If you make everything public, then another programmer might alter a variable which you don't want changed by anything other than the inner workings of your object.

STATIC MODIFIERS:

  • This makes a method or property only accessible by the class and not by an instance or object.
  • It allows the use of a property or method of a class without having to
    make an instance of it.
  • Static properties can be referenced in methods inside the class by
    using ClassName::$property

Use the static keyword in place of var:

class Class_A {
    static $property = value; 
//the property is attached to the class and
//not the instance of it.
    function funcName {
    Class_A::$property = newValue; 
    //use :: syntax to access static properties.
    }
}

Note: when accessing static data in the Class, use the $ in the variable name if present (as opposed to omitting it when working with an instance).

To access the static property or method:

Insert :: after the class name to access static data: 

Example: 

echo Class_A::$property;

or

Class_A::funcName(); 
//executes the method using the static property.

S.O.L.I.D. DESIGN PRINCIPLES IN OOP:

  • Fundamental OOP design patterns and concepts to make your code easier to maintain, debug and read.

S.O.L.I.D. stands for:

  • Single Responsibility Principle (SRP): Classes should have one and only one job, or should have one and only one reason to change.
  • Open/Closed Principle (OCP):  Classes/objects should be open for extension, but closed for modification. Easily extend a class without modifying it, make functionality in the class as abstract and broad as possible and leave more specific tasks and computation in the sub-classes that extend it.
  • Liskov Substitution Principle:  Every subclass should be substitutable for their base/parent class. The functionality and methods/properties of a subclass should not remove or significantly differ from the functionality/logic of it’s base/parent class it extends, so that uses of it as a type of the parent class will not break or not work as expected.
  • Interface Segregation Principle (ISP):  No client should be forced to depend on methods it does not use.  Interfaces belong to their clients and not to the implementations. Thus, we should always design them in a way to best suite our clients. we should break our interfaces in many smaller ones, so they better satisfy the exact needs of our clients. Interfaces are just plain function name definitions. There is no implementation of any kind of logic in them.. great advantage of clients depending only and only on what they actually need and use.
    *** ISP recommends that you should use many specialized interfaces instead one big interface. Interfaces belong to their clients and should represent what the clients need. This helps reducing dependencies on methods the client is not using.
  • Dependency Inversion Principle (DIP):  High-level modules should not depend on low-level modules.  Both should depend on abstractions.  Abstractions should not depend upon details. Details should depend upon abstractions.  Common solution is to implement Interfaces which are objects that specify what methods are available to classes or objects that implement them.

DESIGN PATTERNS IN OOP:

  • Singleton:  An object of which there is one and always only one copy or instance.  The object is not instantiated with copies that inherit from it or duplicated anywhere else in the application code.  The purpose of using a singleton could include conserving memory space and provide a single instance of an object that serves as a central and global resource that you need to manage throughout the application (i.e. a log).   The pattern is criticized because since it can expose your object to the global namespace, but if used carefully and depending on the use case, it can be an appropriate solution and pattern to implement.

FURTHER READING AND RESOURCES: 


Helpful Bonus Tips:

  • To check if a Class exists use class_exists("class_Name");  returns a boolean.  Can be used for debugging.
  • You can also use method_exists("method_Name"); to check for a method.  Can be used for debugging if trying to find methods in a lot of code.

This blog post is a summary of my notes taken from an online course on Udemy by Edwin Diaz called PHP for Beginners – Become a PHP Master – CMS Project.  There is a section on Object Oriented Programming in the course that was excellent and explained the fundamental concepts clearly and efficiently.   I’ve tried to boil the concepts down into a quick read as an introductory crash course to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.