How to declare a class in PHP

Since PHP 5 we can use object oriented features in PHP. This allows us to not only use functions and variables, but also write classes and create instances of them in our code.

Here’s quick rundown on how to do it.

Writing and instantiating a Class

Creating classes is very similar to writing functions. Here’s an example of a class with one method and one variable:

// creating a basic class with one method
class Test {
  var $testValue = 47;
  function sampleFunction() {
  echo "Hello from the Sample Function!\n";

Once declared, we can instantiate our class like this:

// instantiating the class
$myTest = new Test();

Accessing variables and methods

Now we can access any variables in our instance using the -> operator like this:

// accessing a class variable
echo $myTest->testValue;

The same principle is true for calling methods in our instance.

// calling a method

Constructor Methods

A method is nothing other than a function really, but when a function is part of a class, we call it method. I guess that’s done to differentiate it from a “classic” function that’s declared outside of a class.

There’s a special method we can declare inside our classes called a constructor method. It works just like a regular method, with the only difference that the constructor is called automatically when the class is instantiated. This is useful if we want something to happen as soon as our class is used the first time.

Constructors have a special name (__construct); here’s an example:

// creating a class with a constructor method
  class Test {
    function __construct() {
      echo "Hello from the Test Constuctor!\n";

Extending a Class

Classes can inherit functionality from other classes. When we do that we create an exact duplicate of an existing class. This is useful if we want to change the behaviour of a class, for example by overwriting existing methods or values.

Here’s how we can extend a class:

// extending a class
class MegaTest extends Test {
  function __construct() {
  echo "And Hello again from the extended class constructor.\n";

Overwriting methods and variables is as easy as simply re-declaring them using their original names. Extended classes can be extended again, but a class can only ever inherit from another single class.

Notice the use of the parent:: keyword in our constructor method. When our extended class is instantiated, our constructor method is called. If our parent class also has a constructor method (which is optional), we must call this before doing anything else to make sure that any functionality that is setup is being kicked off.

In essence, anything prefixed with the parent:: keyword will call the related function “one level up”.

Now we can create an instance of our extended class as described above:

// instantiate the extended class
$myMegaTest = new MegaTest();

You can leave a comment on my original post.