Category Archives: PHP

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.

PHP Variable Scope (and how it differs from Javascript)

After learning about variable scope, the scope chain and name space in Javascript, I just wanted to sum up succinctly and briefly my understanding of PHP Variable Scope and how it differs from Javascript for those who might be wondering or learning about the topic.

The main difference between Javascript and PHP variable scope is concerning their accessibility inside and outside of functions:

  • Javascript: Global variables are visible inside functions.  There is an outer reference feature built in the engine that allows for variables in the outer environment to be visible and available in the execution context of a function.
  • PHP: Global variables do not have scope inside functions (unless you use the keyword ‘global‘ preceding the global variable being referenced inside the function to access them).  Variables inside functions, conversely, do not have global scope and are not visible outside of their parent function (you can declare a variable inside a function as global by again using the keyword ‘global‘.)

There is an excellent post on Stackoverflow here discussing variable scope in PHP in great detail.

A key ‘quirk’ to note that might be confusing is to understand that, in PHP, if a variable inside a function is created and declared as global without having existed as a global beforehand, then it’s value will only be retained inside that function, and outside of the function it will be empty.  If the global variable has already been declared in the global space, then referencing it inside a function with the ‘global‘ keyword will allow you to assign it a value that sticks globally.

I didn’t realize how simple variable scope in PHP was.  It probably helps that I already understand variable scope in Javascript fairly well, which is more complex involving Closures, Execution Contexts and the Execution Stack, so getting the gist of it in PHP is more straight-forward in comparison.

Be sure to check out my GitHub page to see what I’m working on currently.  I’m pushing a lot of code and updates and am working feverishly to make progress.  Anyways, I hope this little article helped boil down variable scope in PHP and some of the differences between it and that of Javascript.

 

 

A Key Concept in understanding conditionals: They evaluate to a Boolean.

Something that I’ve learned that has proven to be fundamental in understanding and using conditional statements in Javascript (if, while, etc.) is how and what they evaluate to.  A couple of great articles that explain this in detail are located here and here.  Both are a great read and the articles address and explain the concepts of ‘truthy’ and ‘falsey’, which I have found to be key concepts in using conditionals correctly and effectively.

Basically, conditional statements return a value and then evaluate that to a Boolean equivalent – true or false.  The equivalent numeric value of true would be 1 and 0 would be false (the way I remember this is that it’s like converting the Booleans to binary code which is a computer’s native language).

Something that has confused me lately is this example:

var x = "cat";
if (x > 0) {
alert(x);
}

Before my understanding of how conditionals evaluate, I would have looked at this conditional and read it as: “If ‘cat’ is greater than 0, then execute the code. ”   This would be confusing as ‘cat’ is a string data type and not numeric, so the condition doesn’t seem to make any sense.

But, if one has an understanding that the condition returns a result that evaluates to the equivalent of a Boolean, which has a numeric equivalent (0 or 1), and takes into account coercion in the JS engine, then the code could be understood as:  The condition (x = "cat") returns a value that is a string, and is ‘truthy’ since a string is a primitive data type that converts to a Boolean value of true, or the numeric value of 1.  So, since x holds a value that has the Boolean numeric equivalent of 1, the condition is true, and with this concept being understood, "cat" is indeed greater than 0.  The code will execute…or will it?

On testing this code in the console using Javascript, it did not execute and the condition evaluated to false.  This may be because of a feature (some would call it a ‘quirk’) in Javascript called type coercion which will convert values in an expression if their type is not relevant to the operator’s functionality.  For example, if you are using the + operator for arithmetic, and have one string and one number on either side, Javascript will attempt to coerce the type of the string to a number value.  So, if I console.log(x) after it has been assigned, then it does return a value of true when coerced to a Boolean, which would make it equal to 1.  But, because of type coercion, when “cat” is used with >, Javascript cannot coerce the string "cat" to a number type and so returns a result of NaN (Not a Number), which converts to the boolean false.   So, the expressions in if conditionals, when used in Javascript, need to be composed in a manner that keeps type coercion in mind.

The concept of conditions evaluating to a boolean for if statements (though, not the concept of type conversion) can also be applied in PHP conditionals.  Take the following example:

if ($username && $password) {
echo "Username and Password is set."
}

Without understanding that conditionals evaluate to a Boolean, and the concepts of truthy and falsey, then you would look at this and wonder what the condition is – only a couple variables are listed…what about those variables?  If you understand that the condition is evaluated to true or false, and that a variable is truthy if it ‘exists’ (i.e. is not falsey with a value of ‘not undefined, null, NaN, 0, or false’, and in this case especially, an empty string), then the code will execute.  If the variables are falsey and are an empty string or one of the falsey values listed above, then the code will not run and the user will know that the password and username variables are not set (they are falsey and the condition is evaluated to false).  I think of it like the variable has life in it and exists if it holds a truthy value, and is dead or doesn’t ‘exist’ if it holds a falsey value.  Existence is a key concept also discussed further in the helpful articles mentioned at the top of this post.

I have found that understanding that conditionals evaluate to a Boolean is crucial to understanding various uses of them.  The article mentioned at the beginning of this post does a great job of explaining the concept more thoroughly and I encourage readers to check it out if the above explanation isn’t clear.  Hope this helps out some in any case.