Posts Tagged ‘object oriented programming in PHP’

As a student of Computer Science, and a web developer, one of my passions is PHP, and over the years this language has developed with some quite robust functionality. The topic I will be discussing today is Object Oriented programming. I will give an introductory overview to the concept in general, and provide some code examples. At the end I will discuss why this paradigm is useful.

You should have a working knowledge of:

  • PHP in general
  • Basic programming concepts (flow control, different variable data types, looping, etc.)
First, what is object oriented programming (hereby abbreviated as OOP)? Well in its most basic form, OOP is a programming style in which the programmer separates the differing functionality of his program into distinct objects. For a simple example, consider a program that would simulate a car running. Each different part of the car could be its own object (IE the wheels are one object, the chassis another, and the engine another still). All these objects work together, but separately. The engine tells the wheels to turn, and the wheels tell the chassis to move. This is an oversimplified example, but the point remains the same. All the objects in this program work together to provide the functionality of the program itself.
Now that we have a basic idea of what OOP is, lets start discussing some concepts and vocabulary. First, the basic vocabulary (with code examples) that we will need in order to continue.
Class: This is what PHP calls the prototype for objects. This holds all the information about any objects created from these, including its attributes, methods, etc.
Instantiate: This is the process in which we create an object of some class.
Method: A method is a function that is part of a class, and is only available to the class (IE you can not call a method without an instance of a class)
Attribute/Property: Any variables that make up the class
Private: This defines the scope of a method or property. Private means that you may only access the method or property inside the class
Public: This defines the scope of a method or property. Public means that you can access the method or property anywhere it is available.
Now lets look at a code example that will demonstrate each of these words
class MyClass {
public $property1;//this is a property. set to public scope
private $property2;//this is a property set to private scope

public function Method1(){//this is a method, set to public scope
$this->property2 = "Cool";
echo "Hello World!";
}
private function Method2(){//this is a method set to private scope
echo "You can't see me! Or can you?";
}
public function CallMethod2(){//This is a method set to public scope
$this->Method2();//we can call Method2 here because we are inside the class
}
//note we use the variable $this with the -> operator to access class variables and methods
}//end class

//now lets use our class
$MyClassVariable = new MyClass;//this is instantiating. we just created an instance or object of type MyClass
//we use the -> operator to access methods/properties
$MyClassVariable->property1 = "Hello";//We can access property1 because its public
$MyClassVariable->property2 = "Error! Error!";//We can't access property2 because its private

$MyClassVariable->Method1();//this would output: Hello World!
$MyClassVariable->Method2();//this would produce an error. Remember, Method2 is private!
$myClassVariable->CallMethod2();//This would work and would say: You can't see me! Or Can you?
//we need an instance of the class to call its methods
//we cant do something like
MyClass->property1 = "Something";

Now lets examine what went on here. First we created a class called MyClass, in which I created a few properties and methods. I then instantiated an object of that class, and showed various ways to use the methods and properties (and ways in which you can’t use it depending on the private/public scope of the method or property).

Now you may be thinking, what is the point of private methods/properties? Public kind of makes sense because we can keep certain information together in one class, and still access it, but private means we can’t touch it even if we want to. Well that gets to my next point, which is a concept called encapsulation. This is probably the most basic concept in OOP, the usually the first you learn.

Encapsulation is easy to understand, but may be difficult to understand the usefulness, but I will try my best to explain it as simply as I can. Encapsulation is the practice in which you make certain properties or methods of an object private to protect it from the outside world. Simple enough right? But why would we want to do this? Well consider the following:

Say we have a class called Person, with all the attributes and methods we would expect it to have (Like the property name, the method sleep, etc.) Now, for his name property, we could make it public, but that implies that other people, and other entities in the world would and should be able to change the person’s name. In reality, a person receives his name when he is born (or in programming terms, instantiated) and it doesn’t ever really change (well, ignoring paying to change your name, but lets ignore that for this simple example.) Make sense? There are many different examples we can cite of information that should be part of an object, but really shouldn’t be able to be changed by other people. But, the next questions that may arise would be: How do we ask the person’s name? And how do we give the person a name when they are born? Well that brings me to my next point. There are two special methods we can utilize (well really, one is a special method and the other a type of method.) Called the Constructor and an Accessor.

Constructor: This is a special method which, when defined, is called when you instantiate an object. If you add parameters to this function, you must specify them in the creation of the line (more below)

Accessor: This is a type of method that allows the programmer to access the value of of a private property without being able to change it.

Lets take a code example using our person from above

class Person {
private $name;

function __construct($n){//here is our constructor. this is called when we instantiate a person object, or when a person is "born"
$this->name = n;//set our private data member to passed in name
}

public function getName() {
//this is an accessor. It returns the name of the person
//but doesn't let anyone change it
$return $this->name;
}
}//end class

$bob = new Person("Bob");//we pass in Bob to the constructor. now $bob has a name!
echo "Hello, my name is " . $bob->getName();//echos: Hello, my name is Bob

And there we go, a very basic class that uses the concept of encapsulation to keep its private data safe from the outside. As a general rule, making your properties private, and creating ways to access them is the best way to adhere to encapsulation. Of course, with accessors, there are always methods to change a private variable, called a mutator. I will not be going over that in much detail.

Now, enough of the hypothetical’s, how about we do something useful? Ok, lets create a simple database class that makes use of all the concepts we have discussed so far.

class simpleDB{
private $host;
private $password;
private $username;
private $link = null;//example of setting a default value

function __construct($h="localHost", $p="", $u="username"){//default mysql values
$this->host = $h;
$this->password = $p;
$this->username = $u;
}

public function Connect() {
$this->link = mysql_connect($this->host, $this->username, $this->password);
return $this->link;//return the connection for testing purposes
}

public function Select_DB($database){
if ($this->link){//if its not null
return mysql_select_db($database);
}
return false;
}

public function Query($query){
if ($this->link){
return mysql_query($query);
}
return false;
}
}//end class
The class above could be known as an wrapper class, because it is a class wrapped around existing functionality to put it into a neat little package. If anyone would like an explanation of this class I can try to explain in the comments, but try to figure out how it works, and what parts exemplify which concepts on your own! Hope you guys enjoyed this tutorial