How To Use Classes In PHP

This is a free resource from my online course, From Idea To Launch, where I teach you how to build a full Laravel web application, step by step, at beginner's speed. Learn more →

Classes are reusable, self-contained modules of code, used for specific purposes.

Classes are a great way to organize code because, as mentioned, they’re both reusable and self-contained.

Below, I’m going to give you a rundown of how to create and use classes in PHP.


Creating a class

To define a class, you use the following syntax:


class Html
{

}

Classes can contain variables and functions

So, within a class, you can define variables and functions:


class Html
{
  public $p_open = '<p>';
  public $p_close = '</p>';

  public function printParagraph($text)
  {

  }
}

And, when referencing a class’s own variables from within one of its functions, you use the $this to refer to the class itself:


class Html
{
  public $p_open = '<p>';
  public $p_close = '</p>';

  public function printParagraph($text)
  {
    // prints <p>value-of-text</p>
    echo $this->p_open . $text . $this->p_close;
  }
}

But how do you access that functionality? Ahh, yes … by creating an instance of the class.

Creating an instance of a class

If you think of the class as sort of a “template”, you can create an “object” based on that template; that “object” is called a class instance.

You create an instance of a class using the new keyword, followed by the class’s name:

// creates an instance of the Html class
$myPage = new Html;

And then you can access all of the class’s functionality — via your instance — using the familiar arrow, ->, syntax:

// creates an instance of the Html class
$myPage = new Html;

// prints <p>Whoomp, there it is!</p>
$myPage->printParagraph('Whoomp, there it is!');

Classes also have the ability to borrow the functionality of other classes.

Extending a class

A class can extend another class in order to “borrow” the other class’s functionality.

So, let’s say we have a Vehicle class with variables to represent the vehicle’s info, and a function to display its info:


class Vehicle
{
  public $make = '';
  public $model = '';
  public $year = '';

  public function printInfo()
  {
    // prints "<year> <make> <model>"
    echo $this->year . ' ' . $this->make . ' ' . $this->model;
  }
}

But then let’s say we then want to create a Car class to represent a specific type of vehicles, cars. We can create that class and have it extend the Vehicle class — using the extends keyword — which will let it:

  1. borrow all of the Vehicle class functionality;
  2. and add its own Car-specific functionality.

That would work like so:


class Car extends Vehicle
{
  public function honk()
  {
    // prints "honk, honk!"
    echo "honk, honk!";
  }
}

// a car!
$car = new Car;

// this all works, because Cars
// have access to Vehicle functionality
$car->year = 1981;
$car->make = 'DeLorean';
$car->model = 'DMC-12';

// prints "1981 DeLorean DMC-12"
$car->printInfo();

// but it can *also* honk — specific to Cars
$car->honk(); // prints "honk, honk!"

Last, but not least … what’s all this business with public?! Is there a private?

You betcha. Here goes …

public vs. private

Let me make this as simple as possible.

When you precede a variable or function in a class with public, the variable/function can be accessed outside of the class itself.

When you precede a variable or function in a class with private, the variable/function can only be accessed from within the class.

So, let’s take real-life example. Say you wanted to create a Database class to establish database connections. That class would need the connection credentials, but it only needs to access them from within the class itself.

On the other hand, it needs to access the database connection outside of the class — otherwise it’d be quite useless!

You could define such a class like so:


class Database 
{
  // only accessible *inside* of the class
  private $servername = 'changeme';
  private $username = 'change';
  private $password = 'change';

  // accessible *outside* of the class
  public $connection = null;

  public function connect()
  {
    // INSIDE the class, so can access it all!
    $this->connection = connect_function($this->servername,
      $this->username, $this->password);
  }
}

// Connect to the database!
// works because the connect function is public
$db = new Database;
$db->connect();

// use the connection for something (e.g. to query)
// works because the connection variable because it's public
$result = $db->connection->query('…');