Classes as PHP Functions

A class is a function of PHP that has its roots in object oriented programming. The ability to use classes in PHP has been increasing with later versions. If you want to add the power of classes to your PHP programming, keep reading.

Introduction

Continuing our PHP functions article, we move on to creating classes. Let me say right at the start that you can write perfectly effective and useful PHP code without creating classes or going into object oriented programming. Another thing is that PHP, at its core, is not an object oriented language. This is because PHP was built from the C language, which is at its core a procedural language, rather than a methodical one. However, object oriented programming can be very powerful and PHP programmers are increasingly taking advantage of these capabilities, which have been greatly expanded since PHP4.

What is a class?

A class is a collection of variables and functions that serves a common purpose. It gives you the ability to think about real world objects and translate them into code. For example, let’s try to describe a car. The class “car” might have variables: $name_of_car, $wheels, $steeringwheel, $windscreen, $lights, $pedals and $brakes. The functions of a car might include Turnleft(),Turnright() and Accelerate(). The function “Accelerate()” might take arguments such as $increase_speed. Now, all of the above describes a car and what a car does in both real terms and in code.

Now you might ask, couldn’t  this be done with regular functions and variables? Yes, it could, especially if you were talking about one car. But if you are talking about more than one car, then it would be impossible to keep up with all the various variables and functions associated with multiple cars. This is where classes become very useful, because classes bring all those variables and functions under one name. In this case, it’s an object named “car.” Now if you have more than one car, all you have to do is instantiate that object. The term instantiate basically means making a copy of the object. The new copy will have all the variables and functions of the original object available to it. You can include the class in any script that you create; the class will work the same.

Let me sound a cautionary note. Although OOP makes coding easier and more portable, the objects’ execution time is less efficient than writing straight code. And while OOP speeds up project development drastically, more often than not, it produces less customized and slower applications. So, be aware of these pitfalls when choosing to use OOP.

OOP is arguably difficult to learn, so in this article I am going to use very simple examples to demonstrate how to use OOP. This should help new users grasp the concepts easily. Also, because OOP is such a huge topic I will only deal with the basics so as to give you the ability to easily learn the more advanced aspects of it.

A class has the following members:

Attributes

Methods

A good example of a class is Human. A human class would have characteristics (attributes) of gender, hands, legs, age, and so forth. It would also have actions (methods) such as walking, eating, running, talking, and so on.

The syntax of a class is as follows:

class class_name{
var $variable_name;
function
function_name(){
statements;
}
}

Notice that within the class you use the var keyword to identify your variables. At this point you can also assign a value to your variables. Try to use the same naming conventions as you would for functions. It is easier to recognize what a class is if it reflects its purpose(e.g. class Human_class{). Another keyword, $this, is used to refer to the instances of an object and its attributes e.g. $this->$variable_name. To instantiate a class means to create a new version of it. Say we  have a class called dog, to instantiate it, we do this:

$rex = new dog();

Now, rex will have all the attributes of the class dog.

{mospagebreak title=Creating a Class}

Let’s create a simple class to demonstrate the concepts discussed above. Create a new PHP document called sample_class.php. Our class is going to be called human.

We know that a human has legs and arms, which in our class are going to represent the attributes. And we also know that humans walk, eat and sleep. These will act as the methods.

Script: sample_class.php:

<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
echo “Jude has ” .$jude->legs.” legs”;
?>

Here we have a new object created from our human class, called jude. We also have a simple result saying how many legs Jude has. Note how the variable “legs”(declared in the class) is used without the dollar sign in the echo statement.

As well as calling attributes, we can also modify the attributes in the same way. For example if we want the leg attribute to be increased by say, one, so that legs now equals three, then this is what we do:

<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
< style=”color: red;” lang=”EN-GB”>$jude-
>legs++; //increase legs by one
echo “Jude has ” .$jude->legs.” legs”;
?>

As you can see, we can use attributes in a way that is similar to how we use variables.

{mospagebreak title=Adding an Attribute to the Objects}

Let’ create another instance to see what happens:

<?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
< style=”color: navy;” lang=”EN-GB”>$jude = new human();
< style=”color: navy;” lang=”EN-GB”>$jane = new human();
< style=”color: red;” lang=”EN-GB”>$jude-
>legs++; //increase legs by one
echo “Jude has ” .$jude->legs.” Legs<br>”;
echo “Jane has ” .$jane->legs.” legs”;
?>

…the result..

 

As you can see from the result, we can modify the instance of a class without touching the class definition itself. This re-usability is what makes classes so useful.

Now we can also add a new attribute to any of the objects (jane or jude). For example, let’s add a new attribute to jane. The attribute is hair color:

 <?
class human{
var $legs=2;
var $arms=2;
}
//instantiate the class
$jude = new human();
$jane = new human();
< style=”color: red;” lang=”EN-GB”>$jane->haircolor=”brown”;
$jude->legs++; //increase legs by one
echo “Jude has ” .$jude->legs.” Legs<br>”;
echo “Jane has “.$jane->haircolor.” Hair and was created from the
class <b>”.get_class($jane).”</b> She also has <b>”.$jane->legs.”
</b>legs”;
?>

So if we wanted to do the same thing for jude, we have to type all that out again, which is time consuming. Instead, we are going to automate this process by creating a function that will report on both jane and jude. So let’s change the class to include this function:

<?
class human{
var $legs=2;
< style=”color: red;” lang=”EN-GB”>function report(){
< style=”color: red;” lang=”EN-GB”>return  “This <b>”.get_class
($this).”</b> has <b>” .$this->haircolor. “</b> hair,and
<b>” .$this->legs. “</b> legs<br>” ;
}
}
//instantiate the class
$jude = new human();
$jane = new human();
$jane->haircolor=”brown”;
$jude->haircolor=”black”;
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

The variable $this enables us to refer to the object without knowing its name. Remember, when we created the class, we had no idea that an object called “jane” or “jude” was going to be created further along the line.

We said in our previous discussion that classes have attributes and methods, well, the function “report” is our method.

As you can see from the result above, the report() function has automated the process of reporting the attributes of an object. But we have a problem: not all humans have the same hair color, so we can’t declare the hair color as an attribute of the class, and we can’t create a hair color attribute each time we create a new “human” object, because it will make the code inefficient. So what can we do?

{mospagebreak title=Constructor Functions} 

This “problem” requires us to write special function called a “constructor function.” A constructor function is a function that is written in a way that is very similar to a method of a class. The difference is that a constructor function will be called every time a new instance is made.

The syntax of a constructor function is:

function class_name(){
statements
}

Yes, the constructor function name must be the same as the class name. And within the function you can include all the attributes that are going to be included when an instance of the class is made. So, let’s add a constructor function that will sort out our problem:

<?
class human{
function human($hcolor){
       $this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return  “This <b>”.get_class($this).”</b> has <b>” .$this-
>haircolor. “</b> hair,and <b>” .$this->legs. “</b> legs<br>” ;
}
}
//instantiate the class
$jude = new human();
$jane = new human();
$jane->haircolor=”brown”;
$jude->haircolor=”black”;
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

The ” $this->hcolor=$hcolor;” line will install the hcolor variable as an attribute when a new object is instantiated. So, instead of creating the hair color attribute every time we instantiate a new object, it is automatically called. The new class will look like this:

<?
class human{
function human($hcolor){
       $this->hcolor=$hcolor;
}
var $legs=2;
function report(){
return  “This <b>”.get_class($this).”</b> has <b>” .$this-
>hcolor. “</b> hair,and <b>” .$this->legs. “</b> legs<br>” ;}
}
//instantiate the class
$jude = new human(“black”);
$jane = new human(“brown”);
$jude->legs++; //increase legs by one
echo $jane->report();
echo $jude->report();
?>

Conclusion

This article covered the basics of using functions and classes to make coding faster by cutting out code repetition. In the next part we will focus on inheritance, where one class inherits the attributes of another class.

[gp-comments width="770" linklove="off" ]

chat