article

Classes in PHP

Email
Submitted on: 1/1/2015 1:30:00 PM
By: Dustin R Davis (from psc cd)  
Level: Beginner
User Rating: By 16 Users
Compatibility: PHP 4.0
Views: 68
 
     This tutorial will walk you step by step on how to create and manage classes in PHP.

 
				

 

Introduction

If you are coming to PHP from C++ then you can understand the need to OOP. But for the rest of you, OOP is, in my eyes, the greatest thing to come to programming. Classes allow you to keep track of a lot of information, and to also include function for manipulating that information.

I read something someone wrote and I related instantly. They said that OOP is hard to grasp, but once you understand the concept and the need, it's as bright as day. I could never understand why we needed classes until one day I was working on a project and it hit me.

So why do you need classes? Well, lets say you are making a game. In this game you have multiple players. Lets say for now that the limit is 8 players. You would have to type out and keep track of 8*x variables. x = number of attributes a player has.

Example:

//Player 1
P1_NAME;
P1_SCORE;
P1_AMMO;

//Player 2
P2_NAME;
P2_SCORE;
P2_AMMO;

Now you would have to do this 8 times, so 8*3=24 variables you'd have to keep track of. Lets go on. Lets say Player 2 changed his name. You would have to create a if/else or a switch function to figure out what player he is, and then update his variables.

Example:

if(Player1) {

P1_Name = NewName;

} else if(Player2) {

P2_Name = NewName;

}

you'd have to do this for all 8 players. What a mess!


The OOP Method

Lets take a look at that scenario from an OOP point of view.

You have a multi-player game. This time you want to allow 100 players. Now from the first example this would be a chore to keep track of all this information. But not with OOP! First, we make a class and define an array

//Our class definition
Class cPlayer {

//Our variables
var $Name;
var $Score;
var $Ammo;

//Our functions
function ChangePlayerName($NewName) {

$this->Name = $NewName;

}

}

$PlayerCount;
$Players[PlayerCount] = new cPlayer;

//Lets change the name using OOP!
$Players[PlayerID]->ChangeName("Player3456");

Now how easy was that? Less code, allows for more dynamic code and saves space and time. Lets take a closer look at classes.


The Class frame

You define a class by the class keyword, followed by the name of the class.

class cMyClass {

}

I put a 'c' in front of my class name, just so I know its a class. You can put what you like, but remember, the name has rules. You can not have a name beginning with a number, or use a name that has a space and you can not use a name that is already a keyword or a function name.

You define a variable of type cMyClass like so:

$myClass = new cMyClass;

This says that we want $myClass to be of type cMyClass. Now we can use $myClass to access the variables inside of cMyClass.


The Class guts - Variables

Having a class is no good if you don't have something inside of it. So with this in mind, we add some variables. To add variables, we first identify the variable by putting the var keyword in front of our variable name.

class cMyClass {

var $myVariable;

}

Now we have a variable that we can access. To access this variable you can use the variable we defined for cMyClass.

$myClass->myVariable = "My Class";

$myVariable inside of cMyClass is now set to "My Class". Now, lets say we want to view what is in the variable. You'd assume (as I did) that you can do it this way

echo $myClass->myVariable;

Well, unfortunately, this does not work. Those coming from C++ will be disappointed to hear that you will need to define a function inside of the class to print the value of the variable. See the next section for functions.


The Class guts - Functions / Constructors

The ability to have functions that are specific to your class is great. It is also needed. The first function we will talk about will be the constructor. The constructor is a function that gets called when we create a variable defined as being of type cMyClass. This constructor function has the same name as the class.

class cMyClass {

var $myVariable;

function cMyClass() {

}

}

So what do we do with this constructor? Well, nothing if you dont need it. But, lets say that you want to define $myVariable as having a default value.

class cMyClass {

var $myVariable = "This is a default value";

function cMyClass() {

}

}

This does not work. It will give an error. So this is where our constructor functions comes in. We can set the default value of $myVariable inside this function.

class cMyClass {

var $myVariable;

function cMyClass() {

$this->myVariable = "This is a default value";

}

}

Now, when we define $myClass = new cMyClass; our constructor will be called and the value of $myVariable will be set.

Creating your own functions is just as easy. Just identify our function by putting the function keyword in front of the function name.

class cMyClass {

var $myVariable;

function cMyClass() {

$this->myVariable = "This is a default value";

}

function MyFunction() {

return $this->myVariable;

}

}

in our new function that we just defined, we return the value of $myVariable. Now, you should have a good understanding of how we add functions and variables. Lets take a look at how to access these class members.


Accessing class members

You access class members by using the -> symbol.

$myClass->myVariable;

When accessing class members, you do not need to include the $ infront of variable names.

$myClass->$myVariable = "This is wrong";

$myClass->myVariable = "This is correct";

When accessing class members from inside the class, you will need to use the $this keyword. Follow the same rules as above when accessing the class members from inside the class.

$this->myVariable = "Accessing it from inside";

Accessing our members is not hard. You just need to know how.


Nested classes

At some point, you will want to have nested classes. Nested classes are classes defined inside another class. Take a look at this example:

class cMyClass {

var $myVariable;

function cMyClass() {

$this->myVariable = "Hello";

}

function MyFunction() {

return $this->myVariable;

}

}

class cNewClass {

var $newVariable;
var $myClass;

function cNewClass() {

$newVariable = "Nothing for now";
$myClass = new cMyClass;

}

function NewFunction() {

$newVariable = $this->myClass->MyFunction();

}

}

Now to sort out your confusion. What happened here was this, first, we defined our class cMyClass. Then we define our new class cNewClass. Inside of cNewClass we defined a variable $myClass. Then in the constructor for cNewClass we decalred myClass as cMyClass. Now, we have access to the members of cMyClass from cNewClass.

In our NewClass function we set our $newVariable to the value of cMyClass. We do this by calling the member function MyFunction() of cMyClass to return the value of myVariable. You can also do this from outside of the class like so:

$NewClass = new cNewClass;

$NewClass->newVariable = $NewClass->myClass->MyFunction();


Conclusion
Hopefully I didn't leave out too much information. I tried to cover the basics. OOP is such a great thing that if you are not using it, you are missing out. It allows for easy coding and also allows for more dynamic coding. If you don't understand OOP, I suggest learning.


Other 3 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.