Simple Class Declaration and Initialization with PHP5

If you’re used to classes with C#, C++, and Java, then you’re used to classes in PHP as well. If you’re brand new to classes, I suggest you read up on the definition and uses of them before trying to implement them via this tiny tutorial.

To begin, let’s create a simple class that will store information about a logged in user from a session. This class should hold the user’s username, first name, and last name to identify who it is on subsequent pages and requests. Begin by naming this class as “UserPassport” and adding the three previously described properties. They should not have default values because the class does not make sense without properties assigned during construction.

Expanding on this class, we need to add a constructor and a method to use these properties in a semi-meaningful manner.

There’s nothing crazy going on in the constructor. It’s a simple matter of assigning the properties values from whatever was passed in at construction. To display the information, a displayInfo method is created that places the three values in an array and splices them together separated by a comma and a single space. This value is then echoed to the output stream.

Now, this class is pretty useless if nothing is instantiating instances of it. Below is an example of how to instantiate and display the contents of our class. I used the xhtml 1.1 from The Web Standards Project to define a blank page.

The __autoload method is used to allow auto instantiation of classes without requiring an include statement to the .php file containing the definition. This is often useful if you are like me in the sense that you create one class per file. Without this __autoload method, we would need to have many include statements for each class that we are including. In this specific example, it is unnecessary, but still useful to know for the future.

A new userPassport object is created with initialize values of jsmith for username, John for first name, and Smith for last name. In a real world application, these values would be populated from a database based on login and stored for later use. Calling the displayInfo method on this object will result in the initialized values to be echoed between the HTML body tags as expected.

The resulting output:

jsmith, John, Smith

References:

Leave a Reply

Your email address will not be published. Required fields are marked *