Lesson 13

Defining Classes

Classes are the heart of object-oriented programming. They define what an object looks like, what information it can store, and what actions and calculations it can perform. In this lesson you learn how to create classes.

The basic syntax of a class looks like this:

<?php
class MyClassname
{
  // Properties
  public $someProperty;
  public $someOtherProperty;

  // Methods
  public function someFunction($input = false) {
    // php code
  }

  public function anotherFunction() {
    // php code
  }
}

Begin a class declaration with the word Class followed by the name of the class. The body of the class goes in curly brackets. Put property definitions next, followed by the methods.

The class name can be any combination of letters, numbers, or underscores. It can start with either a letter or an underscore, but, according to convention, a class name should begin with a capital letter. The name is case sensitive. Note that like functions, classes do not start with a $.

It is standard practice to put each class in a file with the same name as the class. So the class Myclassname would go in a file called myclassname.php. This makes it easier to find the right file while you are programming and easier to reuse selected ones in different programs.

If you document your classes with PHPDoc blocks, many editors are able to use them as help text as you program. The block for a class looks like this:

 /** * Class short description * * Class longer description if needed * * @package PackageName ...

Get PHP and MySQL® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.