empire-of-the-crystal

Want a FREE Breaking Bad T-Shirt?

GeekZenith is giving away 3 entirely awesome Breaking Bad t-shirts! Want one? Then head over to The Great GeekZenith Give Away Page and follow the 3 easy steps to enter.

Basic OOP In PHP Part One

Object-Oriented Programming in PHP

Object-Oriented Programming, OOP for short, is a concept that has root as far back as the 1960′s, but has not been in common use within mainstream software development until the 1990′s. With the release of PHP5 in 2004, the PHP code finally gained a whole OOP infrastructure to compete with the likes of Java and C# and the popularity of using OOP in PHP is rising.

In my corner of the world, having a working knowledge of OOP is now a common requirement for many Web Development organisations who have taken to utilising the programming paradigm as a common business practice.

This multi-part tutorial will discuss and examine the basics of OOP in PHP discussing what it actually is, how it works and providing working examples of OOP in everyday PHP development.

Benefits of OOP

OOP refocuses attention on an application’s data rather than logic, shifting focus from a program’s procedural events towards the real-life entities it ultimately models. The result is an application that closely resembles the world around us.

The real benefit of OOP within an organisation is having organised and standardise code that other developers within the company can easily read, understand and use or make amendments where necessary.

Essentially, OOP makes the code easier to maintain, distribute and extend.

Classes

A class in PHP is the starting point of Object-Oriented Programming and it’s a user-defined datatype which contains properties and methods (basically, methods are functions and properties are variables). Classes define the characteristics and behaviours of a PHP object, generally moulding external user definitions into the objects set procedures.

The syntax of a class is set out as follows:


class ClassName {
//properties and methods go here
}

All classes begin with the ‘class’ term, followed by a class name, which is to represent its intended function for easy human understanding and be capitalised concatenated as the example above illustrates. This is recognised as a standardised OOP naming convention for the class function.

Class Example

The following example is a class function that will calculate VAT from a user-defined value and return the results. The example will be written in steps, so feel free to follow the instructions to replicate my example (and hopefully gain a better understanding on OOP syntax along the way), but the source files will be made available for download.

Step 1 – Setting up the Files

Create two new PHP files. Call one index.php and the other class_lib.php. As you can probably already tell from the titles of the files, the index.php is where we will both define our starting data (in this case a figure we will get our class to retrieve VAT for) and display the data from the class (in this case, the actual VAT figure). In class_lib.php, we will define the class, issue properties and create a method to both calculate the VAT and to then return it.

On your index.php page, include the class_lib.php page with a standard PHP include:

include('class_lib.php');

Step 2 – Creating the Class

In the class_lib.php page, enter the following:


class VAT {

}

Step 3 – Creating a Field Declaration

Now that we’ve defined the class, we’ll need to assign a field declaration, or variable, so that we can stuff it with the VAT calculation data inside it and return the consequent values. We’ll call our field ‘vat and declare it inside our class as follows:


class VAT {
public $vat;
}

The above public declares the field declaration as an open variable to be accessed by all and in the PHP class function you can decide what access levels you can grant, from the options of public, private and protected. For this example, I’ll use the public option and will explain the difference between these options in a separate tutorial at some point in the future.

Step 4 – Creating Methods

Before creating our methods, we first ought to think about what we need it, or even them, to do. In this example, we want the methods to find only the VAT of a user-defined value and return that value, so therefore we will require two methods: one to perform each of the aforementioned tasks.

As previous stated, methods in PHP OOP are basically PHP functions housed within classes. First, we’ll create a function to deal with the VAT calculation which we’ll call CalcVat:


class VAT {

	public $vat;

	function CalcVAT($figure) {
	$this->vat = ($figure * 1.175) - $figure;
	}    
}

Seems a little daunting? That’s ok. Let’s break it down.


function CalcVAT($figure) {
}

Here we’ve created a function called CalcVAT, with a built in variable called $figure. This built in variable will be the user-defined figure for which we’ll base our VAT calculation upon (this will become clearer when we call to our function later on in the tutorial), but basically when the function is called the user defines a value and the function assigns this value to the $figure variable.


$this->vat = ($figure * 1.175) - $figure;

This line of code actually performs the VAT calculation. $this->var calls to our previously declared $vat variable, which we then assign the calculation to. The calculation multiplies the user-defined value in order to get the VAT plus the user-defined and finally subtracts the same user-defined value to get the final VAT price.

If you’re wondering about the $this->vat section of the code, it should be noted at this juncture that $this-> is a set operator function in PHP which implies that you’re referring to the field stationed in the same class that is being accessed and manipulated. Essentially, $this->vat is called to our public $vat field we defined earlier and placing the VAT value inside it.

Now that the VAT has been calculated and the results stored, we now need to create the function to return the value. We’ll call this function GetVat see below:


class VAT {

	public $vat;

	function CalcVAT($figure) {
	$this->vat = ($figure * 1.175) - $figure;
	}
	
	function GetVat() {
	return $this->vat;
	}

}

As you can see, the GetVat function simply returns the $this-> operator variable.

Step 5 – Creating Objects

Now set up a PHP object in which we will call to the VAT class and later define the value in which the VatCalc will use to calculate the VAT of the input value.

Go to the index.php we set up earlier. This page should be blank aside from opening and closing PHP tags and of course our class_lib.php include. The standard syntax for creating a new object is:


 new *object/class name* (); 

We will also need to assign this object to a variable in order for us to call to the methods contained with our class. We’ll call this variable $vatPrice. So if we put all of this together for our example, it will be:


include('class_lib.php');
$vatPrice = new VAT();

Step 6 – Accessing Class Methods and Defining Values

The next step is to actually access the methods inside of our class and give a number in which it calculates the vat and then returns it.

The first thing we need to do is to assign our previously created CalcVat a value for it perform its calculations:


$vatPrice->CalcVat("500");

So all together that’s:


include('class_lib.php');
$vatPrice = new VAT();
$vatPrice->CalcVat("500");

As you can see, in order to access the function, we took the variable we assigned our class to – $vatPrice – and called to the CalcVat method within using the -> operator to direct us there. Inside the CalcVat we’ve assigned the value as 500, which within our class_lib.php file is picked up by the CalcVal method within the $figure variable – in essence we’re assigning $figure the value of 500 to then perform its calculations (obviously, the 500 is just an example in this case – i.e. user-defined – and therefore can be anything).

Next, we must retrieve the calculate VAT price from the class. To do that we need to access the GetVat method much the same way as we did the CalcVat method, except this time we don’t need to assign it any values:


echo $vatPrice->GetVat(); 

But we’ll spice it up a little:


echo 'You would have to pay: £'.$vatPrice->GetVat().' in VAT.';

And all together:


include('class_lib.php');
$vatPrice = new VAT();
$vatPrice->CalcVat("500");
echo 'You would have to pay: £'.$vatPrice->GetVat().' in VAT.';

If you navigate to the index.php in a browser you should see the following:

You would have to pay: £87.5 in VAT.

Any questions or problems? If so, leave a comment below. In the meantime, here are the files created for this tutorial for you to download.

No related posts.

10 Responses to Basic OOP In PHP Part One

  1. Thanks for learning me the basis of oop in PHP! I’ve done some oop in Java, but I work a lot more in PHP. I think it’s good practice to program object based.
    Keep up the good work!

    Greetings from a amateur programmer who lives in The Netherlands

  2. The Master of Awesomeness says:

    Hi Duco,

    Thanks for the comment (and apologies for the tragically late reply)!

  3. John says:

    Thanks for the tutorial, found it useful.

  4. Pingback: watch movies online free

  5. Pingback: Alimentos para Perder Peso

  6. Cartoon DVD says:

    Most interesting to learn the best practice way of doing it, rather than the ‘quick’ way of doing it. I can see how this will be really beneficial when attempting larger projects with many more lines of code. Thanks.

  7. Ed says:

    Very good tutorial. Can I make a suggestion.
    The $vat variable in the class should be made private not public. It is only accessed from within the class, there is no need for it to be (public) directly accessed from outside the class.

  8. Ed says:

    Sorry, I just found you address public and private on a later tutorial page.

  9. Amos says:

    would choose to thanks for the efforts you have made in writing this write-up. I hope the same best work by you sometime soon as well. The fact is your creative writing abilities has motivated me to begin with my own site now.

  10. kumar says:

    Well written example to explain the oops concept.please keep up the good work and expecting more
    Tutorials.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>