Php basics [all you need to know]

Coding (Php 7.x)


From where it comes from to where is going to be, Here is all you need to know to write in PHP
 
/img/blog/php-basics.jpg

PHP has been one of the best programming languages of the last 2 decades,


Its simplicity of use and power created and still create plenty of successful careers.


Not to mentions the presence of CMSs and PHP frameworks such as WordPress and Laravel that are currently running the internet despite there is a new trendy language every week.


But,

 

to improve in this language you must know what you don't know.


...and then go to practice it.

 

So go get a nice cup of coffee because, in this long post, I will give you an introduction to all there is to know about PHP and get you up and running for your next job.

 

Fast Links:

 

 

The PHP Biography

 

PHP, as it's known today, is actually the successor to a product named PHP/FI.

 

It was created in 1994 by Rasmus Lerdorf, the very first incarnation of PHP was a simple set of Common Gateway Interface (CGI).


Over time, more functionality was desired, and Rasmus rewrote PHP Tools, producing a much larger and richer implementation. 

 

This new model was capable of database interaction and more.

 

In June of 1995, Rasmus released the source code for PHP Tools to the public, which allowed developers to use it as they saw fit. 

 

The syntax itself was similar to that of Perl. 

 

In fact,

 

to embed the code into an HTML file, developers had to use HTML comments

 

FI continued to enjoy growth and acceptance as a CGI tool, but still not quite as a language. 

 

However,

 

this began to change the following month.

 

In October 1995, Rasmus released a complete rewrite of the code.

 

The language was deliberately designed to resemble C in structure, making it an easy adoption for developers familiar with C, Perl, and similar languages. 
 

The code got another complete makeover, and in April of 1996, combining the names of past releases, 


Rasmus introduced PHP/FI.

 

This second-generation implementation began to truly evolve PHP from a suite of tools into a programming language in its own right.

 

It included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support, and much more.

 

That June, PHP/FI was given a version 2.0 status. 

 

Though it lived a short development life, it continued to enjoy growing popularity in the still-young world of web development. 

 

In 1997 and 1998, PHP/FI had a cult of several thousand users around the world. 

 

A Netcraft survey as of May 1998, indicated that nearly 60,000 domains reported having headers containing "PHP", indicating that the host server did indeed have it installed.

 

This number equated to approximately 1% of all domains on the Internet at the time. 

 

Despite these impressive figures, the maturation of PHP/FI was doomed to limitations; while there were several minor contributors, it was still primarily developed by an individual.

 

PHP 5

After a long story and the creation of the Zend engine the most common version, PHP 5, was released in July 2004. 

 

It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.

 

PHP's development team includes dozens of developers, as well as dozens of others working on PHP-related and supporting projects, such as PEAR, PECL, and documentation, and underlying network infrastructure of well over one-hundred individual web servers on six of the seven continents of the world. 

 

It is safe to presume PHP is now installed on tens or even perhaps hundreds of millions of domains around the world.

 

The current version: PHP 7

Released on December 2018,

 

7.3 is the last stable version of PHP at the moment I am writing this post,

 

There have been several improvements in the syntax but the main difference between this and the precedent version is its speed of execution.

 

PHP is so fast that we went straight to the 7th version skipping the 6th altogether.

 

Jocking aside several tests at PHP benchmark demonstrated that in some occasions now it can process code ap to 50% faster caching up with more trendy backend languages such as Python and NodeJs.

 

The syntax has improved a lot as well, in fact, the core team has been focused on improving the readability of the code by providing  some more keywords and deprecating unutilized methods

 

The updates of PHP 7.3 can be categorized into 4 main categories.

 

The new syntax, the deprecations, then the new features and changes to the core.

 

About the new syntax, we got updates to the heredoc and nowdoc that are now less strict and easy to use, if you like to use array ofter you be glad to know that now the trailing comma has been allowed and do not throw any error or warning anymore.

 

The other update is on the list function, which now gives the possibility to add an element of arrays to variable even buy reference.

 

Regarding deprecations it is now not possible to use the image2wbmp() function anymore, it was a duplicate of imagewbmp() and has been removed to make the language faster.

 

Other space has been freed up by the deletion of a few flags of filter_var() into specific FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED.

 

Lastly,

 

you have to explicitly declare the constant case-sensitive by passing the third parameter of the function as true.

 

The new features are the most fun part of this new release.

 

Let’s start with json_decode(), In case of invalid input, it returns a null variable, even though null is a valid object for JSON to decode to.

 

This made debugging data in JSON format incredibly difficult. 

 

Now instead we have the option to make json_encode and json_decode throw exceptions on errors,

 

The new \JsonException is a subclass of \Exception, and it is now declared in the global namespace.

In the previous version, several functions used to create an error. 

 

One example is the count() function in PHP 7.2 on non-countable elements of the scripts.

 

Countable elements are arrays and objects whose class implements the \Countable interface. 

 

PHP 7.3 now has the is_countable() function.

 

It returns a boolean depending on the passed variable.

 

The last features that have been introduced to the language are the array_key_first() and array_key_last() functions.

 

The goal of both of them is quite self-explanatory,

 

they allow you to get the keys of an array without using other methods such as foreach or changing index.

 

Other main changing on the core of the language PHP 7.3 are changes in the Perl Compatible Regular Expressions.

 

PHP used to use version 8 of the PCRE library, but, from now on PHP is going to use PCRE2

 

Even though it is clearly the successor, PCRE2 has to be considered to be a completely different and new library.

 

PCRE2 is stricter when validating string pattern.

 

The result is that you need to be more careful expecially when using funtion like preg_match().


 

The state of PHP 8

We don’t know much about the new version of PHP,

 

But we know that development has already started.

 

On a Reddit Threat started at the beginning of the year several PHP passionates wrote that PHP 8.0 is a working in progress.

 

Spying at several commits made by Dmitry Stogov one of the main programmers at Zend we can find out that one of the main changes will be the implementation of a JIT compiler,  a PHP interpreter to put it in simpler words.

 

JIT is a strategy in which the software is translated or maybe is better to say compiled on the fly, editing it in a shape that is smaller and faster to be executed.

 

The compiler has access to the runtime whereas a standard compiler doesn’t.

 

It will result in performance improved, 

 

I must say that there have been several previous attempts to build a JIT(Just-in-time).

 

Even though the core team managed to make it work, there wasn’t a real improvement in performances, the reason being that in PHP every process typically lives for a short period of time, whereas in other languages like NodeJs the processes are running continuously.

 

Regarding dates and official releases, PHP 7.4 is supposed to be released in the last month of the year, and it will have a basic version of JIT.

 

About the major release of PHP 8 rumours say that we will all see it in late 2021.

 

Let's talk code: Constructs

 

PHP provides several constructs,  

 

constructs are not functions, they cannot be called as a callback function and they follow different rules than function when we compare them about parameters and parentheses.

 

Whether you are new to programming or a veteran with several decades in coding software you will end up using construct every day for the rest of your career.

 

I have alredy written a series of blog posts in which I illustrate and describe in details all the construct available in the language.

 

Here I will just touch upon some of them,

 

The most used hands down are: echo, print, die, return, isset and require.

 

Constructs in PHP supply solutions for a broad range of objectives.

 

They go from include files into another file to kill the application passing by show data on the browser and check the status of various variables.

 

Variables

 

In PHP and all the other programming languages, variables are used to store information within the software.

 

There are several rules that must be followed when working with variables.

 

In PHP all the variables are prefixed by the dollar sign $.

 

PHP is a loose type language, it simply means that the value of a variable can change throughout the code and the current value is considered its most recent assignment.

 

To assign a value to a variable you need to use the equal operator (=) putting the name on the left-hand side and the value on the right.

 

There are 2 categories of variables simple and compound, in total 8 different variable type is PHP

 

They are:

 

  • Integers whole numbers, with no decimal point
  • Doubles  floating-point numbers
  • Booleans this variable can have two values, true or false.
  • NULL a variable with one value by default
  • Strings include characters, it is surrounded by quotes
  • Arrays compound variable is a collection of other values.
  • Objects another compound variable it contains values and functions that are specific to a class.
  • Resources this is a special variable type, it holds references to resources like file or connections.

 

As written above since PHP is a loose type programming language, you can assign a type of value to a variable and change it throughout your code, you can even evaluate values like they were of other types.

 

Actually,

 

PHP does an amazing job on automatically converting type when needed.
 

Operations

 

In programming languages is often required to do some type of operation, especially, when working on complex systems and creating complex calculations.

 

 

PHP supports 5 types of operations.

 

They are:

 

  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operator

 

Arithmetic Operators

This category is divided in other 7 different operations,

 

The majority of them are really easy to understand, you have been actually studied them in primary school and they are: sum, subtraction, multiplication, and division.

 

They work as you might expect: 

 

You have 2 variables (typically number but it is not mandatory), and insert the operator between them in order to execute the operation.

 

Usually assigning the result to another variable by the assign operator seen previously.

 

Then we have other 3 arithmetic operators, that are less common and a bit more complicated to explain.

 

The first of them is the modulus, recognizable by the symbol %.

 

It returns the remainders after a division, here is an example: 6%4 = 2

 

The Last two elements of this category are really simple to understand, they are the increment operator and the decrement operator.

 

To use them you need the symbols ++ and --.

 

You can use these two operators just before or after a variable and they will perform two different operation.

 

If inserted before a variable the increment/decrement will be performed straight away and then the value will be evaluated.

 

In the opposite case,

 

if the operators will follow the variable the value of the variable will remain the same during evaluation and only after the evaluation the number will be incremented or decremented.


Comparison Operators

 

The comparison operators are mainly used during conditions and they return a boolean value.

 

To do a comparison you insert the comparison operators in between two operands and write your code depending on the expected result.

 

The most basic operand is the equal one, indicated by two equal symbols one after another,

 

If the two operands are the same the value returned will be true, otherwise, it will be false.

 

The opposite of this operand is the Not equal operand.

 

It has an exclamation point followed by an equal and it works exactly in the opposite way of the previous one.

 

Then we have the Less than, Greater than, Less than or equal to and Greater than or equal to.

 

All the previous ones use the major and minor symbols like in math.

 

Eventually,

 

the last one is the spaceship operator,

 

It is the last arrived in the family and it made a lot of developers very happy since helped them to avoid several lines of code with just a few characters.

 

The spaceship operator consists of a weird-looking symbol <=> that resembles a spaceship and evaluates the size of two variables,

 

it returns one of three defined values, they can be -1, 0, or 1 depending on the side of the bigger variable.
 

Logical (or Relational) Operators

In every programming languages you will come across during your career logical operator will be a fundamental part,

 

All of these operators are going to return a boolean value and its result will let you define the different path your code is going to follow according to different condition you can establish beforehand.

 

In PHP,

 

there are 4 logical operators, each of them can be used as a symbol or as a literal translation of its meaning,

 

They are:

  • And - when using this operator you must have at least two single conditions, by calculating these condition together you will be able to retrieve a boolean value. This operator returns true if both the first and the second condition are true
  • Or - it works in a similar way for the previous operator, in fact, it also has to have at least two conditions to work. Even in this case, the evaluation of these two conditions will return a boolean variable that you need to use to perform some action. In his case, the value is true if either one of the two elements is true.
  • Not - this is very straightforward, it takes only a condition or parameter, and by prefixing them with an exclamation point we are saying we are going to evaluate the opposite value
  • Xor- I found this one to be the more tricky among them all, it takes in consideration 2 conditions, and it will return a true response if either one of the conditions is true, but unlike the or operator, it will evaluate false in case both the condition evaluate as true

 

Assignment Operators

The operators that belong to this category are really easy to remember,

 

basically the majority of operators in which is present an equal sign fell into this category.

 

Sometimes the assignment operator is used alongside the arithmetic operator.

 

It is not rare to see a += or -= in someone’s code.

 

For multiplication and division, the operators work exactly in the same way.

 

Rarely you will even encounter the modulus assign operator %=, it works in the same way of the latter but its use is delimited to a specific function.
 

 

Conditional (or ternary) Operators

The ternary operator is a manna from heaven if you want to check the simple condition and have no time,

 

this command is used with the combination of an question mark and followed by a colon work in the same way of an if-else statement

 

() ? : ;

 

The condition does not to be written within the parentheses (I like to use them though),

 

then you need to think at the color as per the else keyword you would usually use.

 

If the condition is true the value before the colon will be taken into consideration otherwise PHP will just consider the second instance (the one after the colon).

 

This is very useful when you want to echo a message or assign a value to a variable depending on some conditions and you can now do it in only one line of code
 

Loops

 

If you need to execute the same block of code time and time again loops are what you need to use, 

 

There are several types of loops each one with its own characteristics and features that have to be used is depending on the case.

 

In PHP we have 4 different types of loops,

 

  • For
  • While
  • Do...while
  • Foreach

 

In the beginning, it won’t be easy to understand which loop you have to choose for your web application,

 

but to make it simple each of the loops can be described as a sentence, that will let you clarify the one you have to implement. 

 

 

 

Here are a few examples.

 

I have to repeat this procedure for 3 times.

 

While this condition is true, I want the block of code to repeat itself.

 

Do it!

 

Do it! and then repeat the block if and while the condition is still true.

 

For each person in this list write their names and addresses.

 

Another feature of the loops is that they have an incremental, in fact, in order for the loop to keep going the variable, we are evaluating the need to change in value (or end in case of foreach).

 

If you, as a developer, forget to insert an incremental within the loop, it will run forever blocking the application if not the computer itself due to computer consumption. 

 

You can see the loops explained in a very detailed manner here

 

Not so difficult anymore isn’t it?

 

Let see them in details
 

for loop

 

If you already know how many times you will need to repeat the cycle, then you are going to need the for loop,

 

I have to repeat this block of code for 3 times.

 

The for loop has a very basic syntax composed of 3 elements:

 

The initialization, that is the starting value of the variable we need to evaluate in order to create the loop.

 

The condition which illustrates until when does the code need to keep on going looping,

 

and Lastly,

 

the increment, as we said a few lines above, here is where you increase or decrease the value of the variable you are evaluating for the loop.
 

while loop

While the variable is minor of 10 I want the block of code to repeat itself.

 

Understanding this loop is very straightforward, 

 

Here you have a condition that evaluates a variable, then, if the result of the condition is true the block of code is executed otherwise the script continues.

 

As you can have noticed, this is different from the for loop seen in the previous paragraph,

 

Here there is no certainty of how many times the code within the loop will be executed, in fact, during the execution of the application, we have no idea if the loop will be executed at all.

 

Is not rare the case that the condition is evaluated as false from its first instance and the while loop be skipped as a whole.
 

do...while

This loop looks very similar to the while seen just above, it also takes a condition and according to its evaluation execute a loop or skip the code,

 

Do it! Then repeat the block if and while the condition is still true.

 

The main difference here and the reason why you will choose a do…while rather than a simple while is that, in here you want the code to be executed at least once.

 

After the code has been executed for the first time you can decide if keep on going or get out of the loop and continue with the application.
 

Foreach loop

For each person in this array echo its name and address

 

PHP has a set of absolute classes and interfaces that implements several functionalities to the language.

 

One of these classes is the class called Traversable.

 

This class alongside IteratorAggregate or the Iterator class set how the element should work during a foreach,

 

Array, object and collection are the best suitable element to be parsed by a foreach loop.

 

The difference between this type of loop and the others is the in here you do not know and do not get to decide, how many time you run the cycle.

 

The loops end when the elements inside the variable end.

 

Since there is a way to control the amount of data you get through the use of limits on a query or the use of construct such as continue and break,

 

this is a very useful feature when retrieving data from a database.

 

I wrote a lot more about traversable and other interfaces inside my Loops in PHP series.
 

 

Conditions

 

You have already seen the ternary operator above. 

 

In a certain way,

 

it can be seen as a conditional statement.

 

There are other conditional statements in PHP and they all depend on the amount of conditions you are forecasting to have.

 

A condition will be evaluated as a boolean value and decide the block of code to execute accordingly.

 

If the condition is true then the code will be executed otherwise, depending on the type of condition you choose to use there are going to be a different result.

 

The conditional statements are very easy to understand and all of them use a simple and clean syntax.
 

The list of the conditions in PHP is the following:

  • If - Only one condition, if true the code will be executed otherwise skipped; 
  • If...else - There are two blocks of code here, the fist will be executed if the condition is true, otherwise the block to be executed would be the one under the else statement. if the script pass from here something will be executed for sure;
  • If...elseif...else - This is usually used in case the web developer expects to execute three or more possible, you can insert as many else if you desire, each of them with its own condition if none of them is true, the code executed will be under the else statement;
  • switch - if you have 4 ore more routes that your code can take, you should consider using a switch instead, it provides a series of the case statement in which you can define all the blocks of code you want to execute and a default case in case all of the previous condition is evaluated as false;

 

Here is a blog post about these explained in a very detailed way

 

 

Arrays

 

Arrays are variables, 

 

but, I believe that arrays deserve a paragraph for themselves in this article,

 

Arrays are incredibly useful.

 

An array is a special type of variable, they are called composite variables, which means they can collect several values in one single variable.

 

Usually,

 

An array does it by the use of a number called index (and they take the name of a numeric array) or by key/value pairs (associative arrays).

 

it is not limited to contain scalar elements, which means you can insert an array into array creating something usually called multidimensional array.

 

This makes the code a lot more complex to use, and sometimes requires loops within loops in order to be parsed.

 

It is not ideal and low in performance but if used in a proper manner it can also be exploited and make the data retrievement much easier.

 

In fact,

 

when a web developer is able to master them, he can create a matrix and take advantage of dozens of functions built-in inside PHP.
 

If you want to check them out, I went over a lot of them in my series “Array function Exposed”

 

 

Sessions & Cookies

 

In the last episode,

 

I have briefly mentioned how sessions works,

 

here we delve into the explanation.

 

In simple words a session is a method that allows the developer to store the information of the user across different pages of the web application.

 

To make it easy think at all the website with a log-in system you came across in your life.

 

All of them store your name or username somewhere so when you browse around the pages of the website you are still logged and your details are still visible on the top menu.

 

we have several examples of this with every social network you are registered in and in any Google services

 

The computer must know who you are when you start and end to use the application.

 

The reason for this is common usage and security issues.

 

The problem developer needs to solve is that an HTTP address is stateless.

 

The aim of sessions variables is to get to the bottom of this issue by saving some of the information of the user and make them available on all the other pages that require authentication.

 

This is a global variable and it is an array, here is an example below.

 

$_SESSION[‘username’]

 

Session variables last until the user closes the browser and unlike a cookie, which is the topic of the following paragraph, all the information available is not stored on the machine of the user.

 

 

 

Cookies are a similar concept but they differ from a session in the way they actually work,

 

First,

 

a cookie is not a variable that you store on the browser, a cookie is an actual file, very small in size that the server deposit on the user’s machine.

 

Here is why during the last couple of years all the website that uses cookie need to have a pop up that let you know about it or ask for permission to access your computer.

 

Every time the same computer request some pages on a browser, the cookie will be sent as well.

 

When you set a cookie some of the parameters requested are the expiration date and the path (the pages of the website) you want to enable the cookie on.

 

Is the job of the web developer using a programming language such as PHP to create new or retrieve old cookie’s value.
 

 

login example & logout

One of the easier exercise you can do when learning about session and cookies is a simple log-in and log-out system.

 

Let’s have a look at some code:

 

(The example above requires a basic understanding of PHP and the ability to create a table in the database using MySql).

 

// Creation of the table using MySql
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
)

// Pretend that a form has been created and its field are username and password


// Connection to the database - connection.php
$connection = mysqli_connect('host', 'username’, 'password');
if (!$connection){
    die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
    die("Database Selection Failed" . mysqli_error($connection));
}

// PHP logic for user login
session_start();
require('connection.php');

if (isset($_POST['username']) and isset($_POST['password'])){
    $username = $_POST['username'];
    $password = $_POST['password'];

    $query = "SELECT * FROM `users` WHERE username='$username' and password='$password'";
 
    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {
        $_SESSION['username'] = $username;
    } else {
        $fmsg = "Invalid Login Credentials.";
    }
}

if (isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
    echo "Hi " . $username . "";
}


// Deletion of the current session on log-out and redirection to login page
session_start();
session_destroy();
header('Location: login.php');

 

This is a really simplified example of a login and logout system,

 

in a real-world application all the MySQL statement must be prepared to prevent MySQL injection and would have been nice if the form would have been style with a bit of CSS

As a rule of thumb, you need to think at every use as a possible menace, every query in MySQL must be prepared, bound and executed

 

 

Object-oriented programming

 

You now know the basic concepts of PHP and after learning the syntax you are going to be able to create a full project using the procedural programming style.

 

But, if you are still reading, it means that you want more.

 

So…

 

Welcome to level 2 of programming!

 

Several months ago I put together a series of articles that define in a very detailed manner what Object-oriented programming (OOP)  is, and how to understand all its principles.

 

For this reason,

 

below I will use a more actionable way to explain, using actual code examples, Creation of classes, actual use of polymorphism, inheritance, etc..

 

One of the easier projects you can do when learning a new programming language is a simple task list,

 

it will be very straightforward to implement and at the same time, it will cover all the concept that you’ll need to learn.

 

Let’s create our personal to-do list using OOP in PHP
 

 

Creating a class

 

The core concept of OOP are objects,

 

Objects are based on classes.

 

In this project, we are creating a to-do list.

 

What is a to-do list?

 

In plain English, it is a list of duties that need to be complete.

 

What’s the core components of a to-do list?

 

The duties or tasks.

 

How does task work?

 

Usually, a task has a name, a description and a state that can be completed or not completed yet,

 

we assume that when we create a new task it has a state of not completed by default

 

So, let’s create a class that is going to represent the tasks we will use on our to-do project.
 

// Task.php
class Task {
    public $name;
    public $description;
    public $completed = false;

    public function __construct (String $name, String $description)
    {
	    $this->name = $name;
        $this->description = $description;
    }
}

 

We have created a class with 3 attributes, as said above the $completed has a state of false by default, and the constructor method that will be called when we create a new task and will store the name and the description into the object.

 

Create instances of the Task class

 

The next phase is to create actual objects passing the 2 attributes required by the construct magic method.

 

$code = new Task('Learn OOP', 'Learn the basics of Object-Oriented Programming');
$rest = new Task('Sleep', 'Healthy minds need to rest, take a 5 minutes nap');
$drink = new Task('Eat&Drink', 'Where is my coffee?');

 

These lines of code are creating new objects that are the tasks.

 

Their names are strings contained in the first parameters, the descriptions are other strings contained in the second parameter.

 

When PHP sees the new keywords, it assigns the values of false to the tasks just created.
 

 

Read the different tasks’ object

 

Now that we have several tasks in our project we able to do retrieve their data.


As you can see even though all of them belongs to the same class Task the content of their data is different for each of the elements.

 

This is one of the superpowers of OOP.
 

echo $code->name; // 'Learn OOP'
echo $code->description; // 'Learn the basics of Object-Oriented Programming'
echo $code->completed; // false

echo $rest>name; // 'Sleep'
echo $rest>description; // 'Healthy minds need to rest, take a 5 minutes nap'
echo $rest>completed; // false


echo $drink>name; // 'Eat&Drink'
echo $drink>description; // 'Where is my coffee?'
echo $drink>completed; // false

 

 

Inheritance, different types of Tasks

 

As you can imagine there can be different types of tasks, they can vary from chores that you need to do at home like 'do the laundry' or 'wash the dishes' to important duty at work such as 'call the client' or 'make a coffee'.


Both these types have the same structure in common, we say that they inherit the structure from the master class Tasks.


To indicate this we use the keyword extends
 

// Chore.php
class Chore extends Task {
    public $name;
    public $description;
    public $completed = false;

    public function __construct (String $name, String $description)
    {
	    $this->name = $name;
          $this->description = $description;
    }
}
// Duty.php
class Duty extends Task {
    public $name;
    public $description;
    public $completed = false;

    public function __construct (String $name, String $description)
    {
	    $this->name = $name;
          $this->description = $description;
    }
}

$chore  = new Chore('Cook, 'Make dinner');
$duty  = new Duty('Coffee, 'Make a cappuccino');

 

 

The concept of Encapsulation on OOP

 

Encapsulation is another of the fundamental concepts in object-oriented programming (OOP). 


It describes the idea of bundling data and methods that work as a single unit in the code, in our case a class.


Encapsulation work alongside another concept called "information hiding",


The mechanism is quite straightforward, you have an attribute that is not available outside the object, to gain access to it (either write or read) you connect it with a public method and hide its specific information.

 

From here comes the practice of using setters and getters methods.

 

As clear from the names, the getter method retrieves an attribute, and a setter method updates it. 

 

You are the one that will decide if an attribute can be read and/or changed, or if it is not visible at all. 

 

Let's change our code and make everything more clear.
 

// Task.php
class Task {
    private $name;
    ...

    public function getName()
    {
        return $this->name;
    }
    public function setName($name)
    {
        $this->name = $name;
    }
}

 

Now the $name variable is private, which means it cannot be accessed directly thus, it can only be visible inside this class.

 

It, however, can be updated and retrieved by the methods created,
 

The keyword "this" refers to the object containing the currently-executing code it clearly specifying that the identifier being referenced is a member of the containing object.

 

 

Polymorphism

 

Another principle of OOP is Polymorphism, 

 

Don’t let this complex word scare you, as the majority of the concept in programming the name is worse than the actual code.

 

To make it simple it only means “many forms”, 

 

When we use polymorphism we are leveraging the benefit of adaptation, the code, in fact, changes its behaviour depending on the given data.

 

Usually,

 

this principle is used via two different ways either abstract classes or interfaces.

 

Since we haven’t used them so far let’s see the interfaces.
 

// TaskCompletedInterface.php
interface responsibility {
  public function complete(Task $id);
}
// Chore.php
class Chore implements Responsibility {
    ....
    public function complete(Task $id)
    {
        ...
        return $this->completed = 1;
    }
}
// Duty.php
class Duty implements Responsibility {
    ....
    public function complete(Task $id)
    {
        ....
        SendEmailToBoss();
        UpdateAgileSpring();
        return $this->completed = 1;
    }
}

 

As you have seen above polymorphism is nothing else than the concept of providing something to action and using the same reference (the method in this case) provide different results.

 

The Chore in the face was simple to set as 1 whereas the once the Duty is completed the script need to notify the boss update the spring and return the value.

 

If this still seems too complicated here is a video format of this concept.

 

 

 

Visibility of methods and attributes

 

Throughout these examples, I am sure you have noticed several times keywords such as public, private and protected.

 

These keywords indicate the visibility of an element of a class and they are used on both attributes and methods.

 

They are actually very easy to understand, let go by order:

  • Public - is the less secure of the three but the easiest to manage, when an element is public is visible for all the other classes and elements.
  • Protected - here we are a little bit stricter, the element of a class indicated a protected can be seen and edited everywhere whiting the class and inside other classes related to the master one.
  • Private - I am sure you understood from the keyword itself private elements cannot be seen from the world outside of the class.  This is used for the payment system and other features that are better to stay under control.

 

 

Magic methods

Magic methods are special methods, prefixed by the symbol __ that can perform special functionality when invoked.

 

There are several of them and in the article below I have described all of them.

 

http://anastasionico.uk/blog/php-magic-methods

 

 

Conclusion

 

That was massive but hope that between this post and the previous one of the series you now have a complete understanding of what developing a project in PHP mean and how you can approach it in the easiest way as possible.


Despite the years,

 

PHP is still one of the principal programming languages in the world, there are plenty of jobs and opportunity to make a career, not to mention is one of the easiest language to use when talking about deploying an application on the web.


If you came so far and you liked this content do not forget to subscribe to the mail list below and get a nice present consisting in the reviews of some of the best book available for Web Development and PHP

 

 

 

 

 

 

 

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Php 7.x) Jun 10, 2019

Learn PHP [the definitive guide]

See details
Coding (Php 7.x) Aug 19, 2019

Good Practices: how to sanitize, validate and escape in PHP [3 methods]

Get full series See details
Coding (Php 7.x) Sep 3, 2019

The code behind Laravel 6

See details
Get my free books' review to improve your skill now!
I'll do myself