This tutorial will walk you step by step on how to create and manage classes in PHP.
Terms of Agreement:
By using this article, you agree to the following terms...
You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
You may link to this article from another website, but ONLY if it is not wrapped in a frame.
You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
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:
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.
I hope you enjoy this tutorial. I tried to explain everyhting in detail. I may have left things out, or over looked a typo, but just let me know. (If this comment was disrespectful, please report it.)
Same problem with me, so i learned it and now i am teaching it. For the tutorial I used dreamweaver to create it, then i copied the code to my submission. I'm hoping more people will do the same. It sure would help out on readability. (If this comment was disrespectful, please report it.)
Yes, this is pretty good for beginners. I just started coding PHP and some PHP-GTK (this is a great idea, this enables a lot of people knowing PHP to make real programs). And this has helped me a lot. (If this comment was disrespectful, please report it.)
Hi Dustin, Nice work as far as syntax and all 'formalities' are related. But me as a C++ student and Web Programming Enthusiast, I dont find your article telling me the need/way to use Classes in PHP. I do my web programming efficiently in Procedural style. But i do agree w/ you on one thing, that OOP is the greatest thing to come to programming. Regards, lexxwern (If this comment was disrespectful, please report it.)
Great formatting--so many people writing articles here don't know how to properly format there work; as a result, we have a lot of good information that is just unreadable. Good Job. I suggest you write a second part to this article with a "real world example." I've written an article for this site and I know how time consumming it is to get it just right for posting--thanks a lot-I hope to see more from you in the future. (If this comment was disrespectful, please report it.)
Nice work. Hopefully you decide to continue this type of work on PSC. (If this comment was disrespectful, please report it.)
5/7/2004 2:26:59 AM:
Good one, cleared my basics of OOP in php.
Thanks (If this comment was disrespectful, please report it.)
8/7/2004 6:45:48 PM:
Fantastic and poignant article. I am self taught in PHP and have been looking for a meaningfull description of what classes are...instead I found a whole tutoria! My scincere thanks for taking the time to share your knowledge with the community.
Cheers! (If this comment was disrespectful, please report it.)
Great article, thanks for posting it. I’m new at PHP and programming in general. I have been struggling, trying to get a grasp on all this information about classes and OOP. Your article and code has helped to clear a few things up for me. Thanks to you, I now see light at the end of this dark tunnel.
Thanks once again for passing on your knowledge to newbie’s like me. Best wishes and hope to learn from you again.
(If this comment was disrespectful, please report it.)
Very well done tutorial. Coming from a Java OOP stand point, I fully understand this. However, I feel if I didn't already have a grasp of OOP, I woudln't understand it nearly as much as I do now. Maybe you should go in to further detail about each specific in the OOP style? (If this comment was disrespectful, please report it.)
Good. (If this comment was disrespectful, please report it.)
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.)