most people seem to think they first need to tell you why you should bother with all this before they tell you how to do it, but i'm not not going to do that. you certainly do not need to write and use classes in php, but if you are here then chances are you want to know some more about it. if you read this and decide that you have no reason to write your own classes, then you are probably right and i will not try to change your mind, but hopefully the reason will be something other than not knowing how!
in this tutorial i will guide you through the evolution of some php code as it passes from being a function through a static class and finally end up as an object. there is plenty more i could share with you on the theory behind objects, but all we are looking at here is giving you the understanding you need to be able to go out and write your own classes. if you decide you want to go into the theory, you can easily find some general oop books or web pages that will go into that.
a good place to start is by giving a shout out to classes and objects you may have already used, and by that i mean PEAR::DB. if you have not used PEAR::DB, it is a collection of classes that help make php code that accesses databases more portable across different database providers (such as mysql, oracle, or postgresql). the first thing you do with PEAR::DB is connect to a database:
some time after that you probably want to get some information out of the database:
both of those examples are using functions from PEAR's DB class. somewhere inside PEAR, both connect() and query() are defined as functions inside of a class named DB. this may be a little confusing now, but i haven't really explained anything to you yet. keep PEAR::DB in the back of your mind for now, and we will go thorugh a review of (or introduction to, depending where you're coming from!) functions.
functions are important to us here because they are commonly used within classes. i am assuming that you have at least some exposure to functions so this will just be quick. for this example, we will be looking at a few functions that will help us build an html form. i've actually used these functions on my website already, so you may find them useful. we will continue using this example throughout the tutorial, so if you hang in there you will also see a couple versions using classes (i also used or am using those versions on my site).
most forms have input tags in them, so we will start with a function that builds an input tag, which we will call forminput. The code would be as follows:
the actual code there is wrapped inside braces that follow the function keyword. this means that when php parses this code, it will remember it with the name of the function (in this case, forminput). the comment below the function shows how it would be used. inside php code, you would call the name of the function, and php understands that to mean what we have defined it to mean.
notice we are also passing three values ('fieldname', 'defaultvalue', and 25) through our function call. these values get assigned (in order) to the variables $name, $value, and $maxlength inside the function. if you look at the function code you can see that we are referencing these values.
you may have expected to see an echo or print command in the function so that it would actually print the code for an html input tag, but instead we see the return command. all functions may have the return command (though it is not always needed), and it is also legal to use it by itself. since we follow the return command with a value, this value will actually be sent back as the value of the function. so the code in the usage comment receives the value returned back from forminput and then prints it out. we could just as easily have made the function use an echo statement and then replaced the = when we call it with a space, but this way you get to see what return does.
there are of course more advanced things you can do with functions, many of which are useful when writing classes, but this should be adequate for understanding what we will be looking at. we're ready to take this example and turn it into a static class!
to put things simply, a static class is a collection of functions grouped together under a single class name. for this to make sense we should probably add another function. this function writes out an option tag for use inside a select tag, and selects it if $default is the same as $value:
now let's put both these into a static class named FORM. names for classes have the same restrictions as names for functions (which we haven't discussed here). we'll start just by defining the empty class:
looks rather a lot like a function definition doesn't it? the differences are that it says class instead of function, there are no parenthesis with variables in them, and we will actually be putting functions inside it rather than direct code. speaking of that, let's add our two functions:
now that we've put these functions inside the class, we need to call them differently. instead of just saying forminput, we need to say where it comes from and say FORM::forminput. all static calls to functions take this form: class name, two colons, then the function name. if you recall, DB::connect follows this form, and yes it is a static function call.
since we are using the name of the class to call these functions, there names are a little redundant (as we have to type FORM::form...), so let's drop 'form' and change the functions to input() and option(). If we had named our functions in this way before, that would have been a poor choice because 'input' or 'option' doesn't go quite far enough to tell you what it means. When we put it inside of a class though, it's identity depends on that class, so you no longer look at input() -- you look at FORM::input(), as input() by itself has no meaning. even while writing php code inside the FORM class, we still need to refer to any of its functions in this way -- if we wanted to call the input function from within the option function (which wouldn't actually make sense to do, but nevermind that), we would still have to say FORM::input so that php can find it.
static classes give us a way of grouping functions together. the function names only have meaning when referenced through the class name such as FORM::input(). this means that should you have a reason to, you can define an input() function that belongs to a different class or even one that does not belong to a class and still use it at the same time as FORM::input(). here is the code for our FORM class again, but with the function names changed:
the only changes we've made from our original functions is to put them inside a class and change their names--we now have FORM::input() instead of forminput() and FORM::option() instead of formoption(). but this isn't all that classes can do! we can also make classes that are not static but instead remember information between calls to functions from that class. in the next section we'll add to our FORM class and use this.
we will start here by changing our two functions to actually write out the html rather than return it. this isn't neccessary in order to make this class into an object, but it gives us a reason to do something later:
now if we care about indentation so that the generated html is easy to read, we may want to write some spaces in front of what we are writing out from these two functions. since they belong to the same form, we can base their indentation off the same reference point. the option tag should be indented one level further than the input tag because option tags need to go inside select tags which would be at the same level as input tags. we will be using two spaces per level of indentation here, so let's add that to our option function:
i'm only showing the option function because that is all that changes. as i said before, we probably want to indent the whole form by some reference level. this is a good candidate for the FORM to remember between function calls, so let's introduce something new and add a variable to the FORM class. any variables you want to use for remembering information between function calls should go between the class line and the first function, and you specify them with 'var $varname' as follows:
notice that like our functions, $indent only exists within the FORM class. if we were still working with FORM as a static class, we could reference it as FORM::indent both inside and outside the class. this time we are going to use to FORM class to create an object, so we need to change the way we access the variables and functions we've defined inside the class. it is actually slightly different if the code we are writing is inside the class versus outside the class, so we will start with how to access our indent variable from inside the class.
i mentioned that we will be using our FORM class to create an object, which means we are going to assume that an object has already been created before anything inside the class is accessed (we will cover how to create objects later). when we make an object from the FORM class and then call one of the functions within the class, we get inside that object. to refer to the $indent that belongs to us, we use a special object called $this, which always refers to the object that we are currently inside. so instead of saying FORM we now will say $this. one other thing must change though, and that is the way we add on the name of the variable/function. a static reference starts with class name, then has :: and the variable/function name. an object reference from inside the class starts with $this, then has -> and the variable/function name. to access $indent from within input() we need to actually write $this->indent instead of just $indent:
i've added it to both functions here as it is the same for both.
now let's look at creating an object from this class. this is actually very easy. the following code would be somewhere outside of the FORM class and creates an object named $form from the FORM class we've defined:
all you need to do is say you want a new object from the FORM class, and assign that to your object variable. it is not actually important to use a name like $form when working with a class named FORM--we could have called it $x if we wanted, but $form is probably more descriptive. if you were actually going to use this, you could be even more descriptive and name it $signupform or something similar. it is also perfectly fine to create more than one object from the same class--each object will have its own copy of $indent in that case. if you created $form2 in the same way that we created $form, you could set $indent on one of them to 4 spaces and the other one could be set to 8 spaces.
since we now have an object, let's look at how to access the variables and functions that are inside it. we actually do this the same way as inside the class, except now we know the name of the object, so we use that instead of $this. for example, we probably want to set the value of $indent inside this form:
note that $form->indent only has meaning after we've created the form object from the FORM class by setting it to new FORM. the creation of the object is what gives us the context of the FORM class--again the input variable only exists in the context of FORM. we would similarly call our two functions by putting their names after $form-> -- just like we did with static calls when we put the names after FORM::. speaking of static calls, with our changes to add $this->indent to our functions, we can no longer call them statically without getting an error, as $this has no meaning unless we have an object.
we can make our FORM class even easier to work with by combining the first two steps of creating the object and setting the value if $indent inside of it. the way we will do this is by adding a constructor. each class may have one constructor, and it will automatically run when we create a new object from that class. a constructor is defined like any other function, except its name must be exactly the same as the name of the class. a constructor may also be set up to accept variables just like any other function. let's add a constructor to our FORM class that will allow us to set $input when we create the object:
i am not showing our other two functions here because they do not change. notice how this looks exactly like a regular function. it's called differently though: the constructor is the one function that does not need to be called from an object. this actually makes sense because the constructor is creating the object, and you can't ever create the first object if you need to call the constructor from an object! so how do we use the constructor? we actually already have used a constructor before when we said new FORM, but in that case it was the default constructor which only creates the object. now by defining our own constructor we are telling FORM objects that they need to do something else when we create them. we will call the constructor in almost the same way as before, but now we have to add a value for it to use for $indent:
again, the constructor is a special function. the keyword new says that we want to create a new object from a class. we follow that by the name of the class we want to create, and then add any values that the constructor needs after that. here we pass the same value for $indent as we before set manually after creating the $form object -- by including our constructor we have combined those two steps into one. now let's use everything in our FORM class to create a very simple html form:
the steps we have to take to use this class are as follows:
that should be enough to get you started using classes and objects, should you choose to. the next section reviews the terms we introduced (as well as some other terms related to classes and objects), and lightly compares php classes and objects with those from some other languages. i've also included the code for the FORM class i am currently using as a larger example.
terms and comparisons
we'll start out with a review of the terms that came up: class - a collection of variables and / or functions constructor - the special function that a class may have, which is executed when an object is created from that class; the constructor must have the same name as the class member - member variables and member functions are variables and functions that are defined inside of a class object - an instance of a class; a variable created from a class that then gains the properties defined in the class; an object reference uses -> oop - object-oriented programming; programming based on objects static - static references use the name of the class and do not require an object to be created; a static reference uses ::
php uses the same syntax for classes and objects as c++ does, in that static functions are accessed by classname::functionname and object functions are accessed by objectname->functionname. some other languages (java for example) use classname.functionname and objectname.functionname instead. both c++ and java allow for parts of the class to be defined as private, which means that you absolutely cannot access those parts of the class from outside the class -- php does not currently support this. java also requires that static functions be specifically defined as static (c++ may support this as well) -- php will let you call any function statically or from an object (though it may not work!). very generally, php supports the use of objects and classes, but it is not at all strict in its implementation.
to wrap things up, I'll show you a more complete example, which is my (somewhat) current FORM class:
No Comments for this page.