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:
create an object from the FORM class, passing any values that the
constructor needs
use the object created to call functions defined in the class
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.