Simple approach to classes and object oriented coding in PHP

Folks, I understand! I really do. You have started coding in BASIC or even Turbo Pascal or you are just copy and pasting Java code around without really getting the hang of it? I have been there and I still suspect the whole Object Oriented Programming thing to be made up by someone with a really twisted mind.

Then I saw the beauty of it: You can simplify your results in code, if you do not follow the REALLY REALLY complicated and twisted tutorials out there. Let us start from a different perspective and say, you can code a little. Nothing you are proud of, but you solve the stuff with loops, ifs and some basic database operations. Complex solutions like WordPress or Drupal have never really kicked your brain and since then you refuse to dig deeper into classes and object oriented architecture. That is a mistake.

Besides many other more complex reasons, let me give you the simple elevator pitch: You can use basic object oriented code to simplify your coding life in PHP.

Let us create your first real simple snippet: a config file.

class myConfig
 static $dbUser = "myUser";
 static $dbPW = "myPW";

So with that first little file, that you might want to save as “myConfig.php”, you start to code with classes. The basic requirement to work with those is to understand the SCOPE OF THE VARIABLES AND FUNCTIONS you use.

The $dbUser variable is only available in the class and you can not access it from your code, just like you would not be able in a function. It is “local”.

Now for variables and functions WITHIN classes, there are keywords to define the scope of the values you use. Here we used “static“.

This key in front of variables means, that you can address/use the variable without creating an instance of that class:

$newClass = new $myClass;

is not needed! You can use the variable with the “::”¬†attribution:

echo myClass::$dbUser;

is possible.

Start with grouping your configuration values like that and in the next few articles we will unveil the additional advantages when it comes to “functions in classes” or what is called “methods”.


One thought on “Simple approach to classes and object oriented coding in PHP

  1. Pingback: Organizing your PHP functions in classes and methods | SNO.PE: Simple Network Talk