Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Defining a Class

OOP programming begins with classes, a class being an abstract definition of a thing: what information must be stored and what functionality must be possible with that information? A User class would be able to store information such as the user’s name, ID, email address, and so forth. The functionality of a User could be login, logout, change password, and more.

Syntactically, a class definition begins with the word class, followed by the name of the class. The class name cannot be a reserved word and is often written in uppercase, as a convention. After the class name, the class definition is placed within curly braces:

class ClassName {

Classes contain variables and functions, which are referred to as attributes (or properties) and methods, respectively (you’ll see other terms, too). Collectively, a class’s attributes and methods are called its members.

Functions are easy to add to classes:

class ClassName {
  function functionName() {
    // Function code.

The methods you define within a class are defined just like functions outside of a class. They can take arguments, have default values, return values, and so on.

Attributes within classes are a little different than variables outside of classes. First, all attributes must be prefixed with a keyword indicating the variable’s visibility. The options are public, private, and protected. Unfortunately, these values won’t mean anything to you until you understand inheritance (in Chapter 5), so until then, just use public:

class ClassName {
  public $var1, $var2;
  function functionName() {
    // Function code.

As shown here, a class’s attributes are listed before any method definitions.

The second distinction between attributes and normal variables is that if an attribute is initialized with a set value, that value must be a literal value and not the result of an expression:

class GoodClass {
  public $var1 = 123;
  public $var2 = 'string';
  public $var3 = array(1, 2, 3);
class BadClass {
  // These won't work!
  public $today = get_date();
  public $square = $num * $num;

Note that you don’t have to initialize the attributes with a value. And, aside from declaring variables, all of a class’s other code goes within its methods. You cannot execute statements outside of a class method:

class BadClass {
  public $num = 2;
  public $square;
  $square = $num * $num; // No!

With all of this in mind, let’s create an easy, almost useless class just to make sure it’s all working fine and dandy. Naturally, I’ll use a Hello, world! example (it’s either that or foo and bar). To make it a little more interesting, this class will be able to say Hello, world! in different languages.

To define a class:

  1. Create a new PHP document in your text editor or IDE, to be named HelloWorld.php (Script 4.1):

    <?php # Script 4.1 - HelloWorld.php
  2. Begin defining the class:

    class HelloWorld {

    Using the syntax outlined earlier, start with the keyword class, followed by the name of the class, followed by the opening curly brace (which could go on the next line, if you prefer).

    For the class name, I use the “uppercase camel” capitalization: initial letters are capitalized, as are the first letters of new words. This is a pseudo-standardized convention in many OOP languages.

Script 4.1. This simple class will allow you to say Hello, world! through the magic of objects! (Okay, so it’s completely unnecessary, but it’s a fine introductory demonstration.)

1    <?php # Script 4.1 - HelloWorld.php
2    /* This page defines the HelloWorld class.
3     * The class says "Hello, world!" in different languages.
4     */
5    class HelloWorld {
7       // This method prints a greeting.
8       // It takes one argument: the language to use.
9       // Default language is English.
10      function sayHello($language = 'English') {
12         // Put the greeting within P tags:
13         echo '<p>';
15         // Print a message specific to a language:
16         switch ($language) {
17            case 'Dutch':
18               echo 'Hallo, wereld!';
19               break;
20            case 'French':
21               echo 'Bonjour, monde!';
22               break;
23            case 'German':
24               echo 'Hallo, Welt!';
25               break;
26            case 'Italian':
27               echo 'Ciao, mondo!';
28               break;
29            case 'Spanish':
30               echo '¡Hola, mundo!';
31               break;
32            case 'English':
33            default:
34               echo 'Hello, world!';
35               break;
36         } // End of switch.
38         // Close the HTML paragraph:
39         echo '</p>';
41         } // End of sayHello() method.
43   } // End of HelloWorld class.
  1. Begin defining the first (and only) method:

    function sayHello($language = 'English') {

    This class currently contains no attributes (variables), as those would have been declared before the methods. This method is called sayHello(). It takes one argument: the language for the greeting.

    For the methods, I normally use the “lowercase camel” convention: start with lowercase letters, separating words with an uppercase letter. This is another common convention, although not one as consistently followed as that for the class name itself.

  2. Start the method’s code:

    echo '<p>';

    The method will print Hello, world! in one of several languages. The message will be wrapped within HTML paragraph tags, begun here.

  3. Add the method’s switch:

    switch ($language) {
      case 'Dutch':
        echo 'Hallo, wereld!';
      case 'French':
        echo 'Bonjour, monde!';
      case 'German':
        echo 'Hallo, Welt!';
      case 'Italian':
        echo 'Ciao, mondo!';
      case 'Spanish':
        echo '¡Hola, mundo!';
      case 'English':
        echo 'Hello, world!';
    } // End of switch.

    The switch prints different messages based upon the chosen language. English is the default language, both in the switch and as the value of the $language argument (see Step 3). Obviously you can easily expand this switch to include more languages, like non-Western ones.

  4. Complete the sayHello() method:

      echo '</p>';
    } // End of sayHello() method.

    You just need to close the HTML paragraph tag.

  5. Complete the class and the PHP page:

  6. Save the file as HelloWorld.php.

    You’ve now created your first class. This isn’t, to be clear, a good use of OOP, but it starts the process and you’ll learn better implementations of the concept in due time.

    Note that I’m not using a closing PHP tag, which is my policy for PHP scripts to be included by other files.

  • + Share This
  • 🔖 Save To Your Account