DDMSEO - Full Stack Developer based in London

Optimize your website SEO with X-RAY SEO Auditor

Published: 1st Jan 2017 | Words: 1,920 | Reading Time: 10 minutes

Categories / Tags:

Development
PHP

Optimising how you build and use code

If you have done procedural PHP you will probably find yourself with a page full of a mix of HTML and PHP code scattered throughout in an unsightly manner which can be hard to read and keep track of. This can really slow down your workflow and can lead to a lot of mistakes if you have to change variables or values because it can be hard to find every instance of everything you want to change. Object Oriented PHP truly is a way to cleanly separate your PHP programming code from your regular HTML. Instead of inserting big chunks of PHP code within your document you can place the PHP programming code within a separate file or files and call whatever part of it you need by placing a small tag within your HTML code where you need the PHP code. You can look at Object Oriented PHP kind of in the same way as you would look at a CSS style sheet. In CSS you usually store it all in an external file and call it when and where needed through the use of tags. If you have done procedural PHP but never Object Oriented PHP you will probably find early on that you can condense your PHP into much smaller blocks of code.

Taking and object oriented approach

One of the biggest advantages is that you no longer have to take a linear approach within your development process. What I mean by this is you no longer have to write a page from top to bottom in terms of your programming, you can write your functions in any order really, and you can call functions from anywhere at any time as long as they are in your class file and it is already loaded. Generally you should separate as much of the programming from the HTML file as possible, all of it really. It makes working on HTML files much easier, and the same is true when you are working on your PHP file. Object Oriented PHP works on what is called classes. Within a class you have various chunks of code including functions. These functions can be called from an external file or you can call these functions within functions. When dealing with classes you will usually refer to functions as methods and class variables as properties. At first it is quite complex but once you understand the basic concept of an object or class you can quickly catch onto how you can streamline your workflow and minimise the amount of PHP code you actually need for a page. When you first work with PHP you will probably look at using functions and variables throughout your scripts. Declaring a function in one place and calling it where needed can save you a lot of code if the function is used multiple times. Instead of writing out the same coding over and over you can build a function with the code within and call it where needed. While building functions and variables and calling them where needed provides you with great flexibility. Working with objects gives you even more.

Object properties and methods

One of the first things about objects that may seem confusing is probably properties and methods. In their simplest forms an object property is a variable and an object method is a function. You may hear many other unfamiliar terms like dependency injection, inheritance, scope and many other things. For now we will look at building a very simple object. You can build an object quite easily using a class. A class in PHP is a grouping of properties / variables and methods / functions.

class simpleClass
{
   // you properties and methods in here
}

A class in PHP is built simply by picking a name for your class and declaring it. You will probably look at having separate files for each of your classes but as your application gets more complex how you group classes can become very complex and how you call your objects can become even more complex. If you think you are ready to build a very complex application with a lot of class files you will probably want to look at a thing called auto loading. If you have worked with PHP files you will know that usually you will have to include your PHP files within other scripts as needed. When you have a few class files using something like a PHP include for each file is fairly straightforward but if you have dozens of class files this approach can quickly lead to a big mess of confusion. For this basic example we are going to just work within one PHP file so auto loading is not necessary as we will be declaring our object within the scope of the class file.

Calling your object

It’s very straightforward to create a basic object. You create a variable and assign the object to it. When you do this you make the properties and methods of the object available to you.

class simpleClass
{
   // you properties and methods in here
}

$class = new simpleClass();

Scope

It does get a bit more complex than this. You can create methods and properties that are only available within the class itself. These may be things that are required to create specific values within the class and should not be called outside of it. Generally classes will build a lot of the structure of your application and build specific values that should be displayed within your pages. Scope plays a key role in stopping you changing values outside of classes that should not be changed and allowing you to change values outside of a class that should be changed.

class simpleClass
{
   public $publicVar;

   protected $protectedVar;

   private $privateVar;
}
$class = new simpleClass();

$class->publicVar; // public works no problem here as the variable is declared as public

$class->protectedVar; // this causes an error as protected properties are only available within the class itself and classes that extend this class (child classes)

$class->privateVar; // this also causes an error as private properties are only available within the particular class itself

To call particular properties it’s simply a case of calling the object in this case $class, using -> and calling the property name. You dont use the dollar symbol as you would calling a regular PHP variable. These basic class properties can have default values assigned to them or their values can be changed in various places throughout your script. You may wish to assign a default number, string, or array to these values and doing this at the top of your class file creates a very structured layout to your application programming and a place where these values can be changed at the top level very easily if need be.

class simpleClass
{
   public $publicVar = array('first', 'second', 'third'); // assign a default array
}

Object methods

This particular way of calling object properties can also be applied to functions / methods within the class. You may have methods you wish to call in global scope but you may also have methods you only wish to be called within the particular class. Classes are meant to be built in a way where related functions are grouped together in a very structured way that allows you and other developers to work with the code within very easily. To declare methods within a class it very straightforward and so is calling the methods.

class simpleClass
{
   function basicMethod()
   {
      return 'This value is returned';
   }
}
$class = new simpleClass();

echo $class->basicMethod(); // this would output "This value is returned"

Hopefully this example is simple enough to understand and gives you an idea of the simplicity of calling object methods. The power of methods is in their flexibility. Methods can take arguments which can be used within them and because of this you can create very flexible methods that produce different results based on the arguments passed.

class simpleClass
{
   function basicMethod($value)
   {
      return 'This '.$value.' is returned';
   }
}

$class = new simpleClass();

echo $class->basicMethod('name'); // this would output "This name is returned"

Any real value could be passed here and it would be substituted within the final string returned and you can also make passing a value optional if need be and have default value in case you pass nothing into the method call. As stated before just like object properties, object methods can be declared as public, protected, or private which will dictate their scope and where they can be called. You do have to work out the logic behind how you declare your object and method scope. When you assign scope you can create a very clear blueprint both for yourself or anyone else who may be working within these files.

class simpleClass
{
   private function basicMethod($value// now this method can only be called within the class as it is private
   {
      return 'This '.$value.' is returned';
   }
}
Rate this article

Average: 0.00 out of 5 / Votes: 0

Comments

Please login or register to post comments

Login | Register