PHP Class Basics

Rube Goldberg Machine
Rube Goldberg Machine

During my continuing journey of learning PHP, one that had bothered me for some time was PHP classes. They seemed mysterious and strictly for advanced uber PHP developers. As a beginner I did not see how they were useful and I was confident that I could use a strictly functional style of programing to get any project completed. This seemed to work for the most part until I was forced to build a web scraping tool to gather web page rankings from google. I ended up building a Rube Goldberg Machine of a function that was nearly impossible to change due to every part of the part of the function being dependent on each other doing a certain thing a certain way. If I changed any part of the function I would almost certainly be required to change every peice of the code to account for the change. After dealing with the abomination of a function that I had created . I made a personal goal to study and learn how to implement an Object-oriented programming style of development into my coding style and have never looked back. It is hard to imagine developing any kind web application with out Classes. The sad thing is if you look around the internet for tutorials or in books for a explination you mainly find two types of examples. One is all theory and no practical real world application for the beginner developer to get a true grasp on how they use OOP in there workflow. The other is a quick glancing view and application with out teaching the basics at the same time. I hope to provide a better example. I am going to break down PHP classes terminology and basic uses for the normal entry level developers out there.

What is a class?

A class can be thought of as a blueprint which is used to build a house or mold use to form inter-changeable parts. A Class is not the actual object that you instantiate in your PHP code. A class is merely the mold used to build the actual object you need. This is the same thing as a mid-evil black smith useing a mold to make a sword. The sword is the object and the the mold is not.

What is a Object?

An object is the thing that is created when you create an object. Creating an object in PHP can be done by including the class file in your php script and using the new keyword.

Example of a simple class

class SomeClass {

    public function hello()
    {

         return "Hello";

    }
}

PHP Script

include 'someclass.php'
$class = new SomeClass();
echo $class->hello();

Results

This would return the string “Hello”.

Setting up a Class

I recommend following PSR 2 standards for defining classes. The standards are more of a recommendation than actual PHP requirments. But as a beginner it would be good for you to familiarize yourself with PSR2 and the PHP Framework Interop Group

All classes must start with the word class and than the class name which must be written out in StudlyCaps.
Example:

class SomeClass
{
    //Properties and Methods
}

Adding code to the class

A PHP class can contain both properties and methods. What are properties? What are Methods? These are the questions I asked at first. Why don’t we just call them variables and functions? I will admit it , it still bothers me to this day that methods are not just called a function and the same thing for properties not being refereed to as a variable. Going forward please understand that methods are just functions and properties are just variables. They will work a little different than normal functions and variables work but I will explain the difference to you. You must also familiarize yourself with the keywords public, private, protected, static, abstract and final. Today we will only cover three of keywords public, private and protected.

public

Using the public keyword on your methods and properties will allow them to be used by the class it’s self and any other sub-classes. I will not not be covering inheritance in this post and will save that for another day. Learning the basics of a class is enough for one day.

private

Using the private keyword on your methods and properties will only allow them to be used by the same class. Sub-classes will not be allowed to use them.

protected

Using the protected keyword on your methods and properties will allow them to be used by the class it’s self and other sub-classes but not directly through the subclasses. ( Yes I know this makes no sense. I will cover inheritance in greater detail another day. )

Properties

Properties are just variables with a few differences. You must declare your properties before the constructor or any methods.

How are they the same? 

  • They can store values to be used at a later time time in your PHP script. 

How they are different? 

  • They must use the visibility keywords (public,private,protected) to define their access levels. 
  • The values of properties must be a static set value. This means that they can not be the value returned from an expression.

How are properties declared? 


// The wrong way.
public $property = $_SERVER['SERVER_NAME'];

// The correct way.
public $property = 'www.example.com';

How they are used in your methods? 

Properties can be accessed using the Object Operator ( -> ) and the $this variable. The $this variable is a special variable that refers to the current object.

class SomeClass {

    //This is a property!
    public $hello = 'Hello';
    //This is a method!
    public function helloWorld()
    {
         //This is an example of using a class property.
         return $this->hello;
         //This will return the value of the $hello property.
    }
}

Methods and the Constructor

Constructor

The constructor is a method that is declared in the class just below your properties. It is a method that is always run every time the class is used to create an object. This is the method that you will want to use to ensure the user has the needed access level to access the methods of the class. A few good examples are listed below.

  • Check if the user is logged in
  • Connect to a database
  • Set values

How do I declare a constructor? 

class SomeClass {

    //This is a property!
    public $hello = 'Hello';

    // This is the constructor.
    public function __construct()
    {

    //code

    }

Can I pass values to the constructor?

Yes, you can pass values to a constructor in the same fashion as you would a normal function in PHP.

class SomeClass {

    //This is a property!
    public $hello = 'Hello';

    // This is the constructor with a value passed to it.
    public function __construct($parameter = null)
    {
    // set the property $hello to the value of the parameter passed to the class.
    $this->hello = $parameter;
    }

    public function helloWorld()
    {

    // return the value of the parameter $hello.
    return $this->hello();
    }
}

//Instantiate the object and pass it a value.

$example = new SomeClass('Hello World');

// Call the method(method is a fancy word for a php function) helloWorld of the SomeClass class.

echo $example->helloWorld();

// returns Hello World. The value of the parameter sent to class when you instantiate( Fancy word for create ) the object

Methods – A fancy word for a PHP function

Methods are used in much the same way as functions used in PHP with just a few differences. A method is declared below the constructor.

How they are different? 

  • All methods are public by default. They can use the visibility keywords (public,private,protected) to define their access levels.
  • You must use the Object Operator ( -> ) on an instantiated object to call the methods of a class.

How to call the methods of the class that has been instantiated as an object? 

Step 1: Create the class. 

class SomeClass {

    //This is a property!
    public $hello = 'Hello';

    // This is the constructor with a value passed to it.
    public function __construct($parameter = null)
    {
    // set the property $hello to the value of the parameter passed to the class.
    $this->hello = $parameter;
    }

    public function helloWorld()
    {

    // return the value of the parameter $hello.
    return $this->hello();
    }
}

Step 2:Instantiate the object

//Instantiate the object and pass it a value.
$example = new SomeClass('Hello World');

Step 3:Use the Object Operator ( -> ) to access the helloWorld() method.


// Call the method(method is a fancy word for a php function) helloWorld of the SomeClass class. // returns Hello World. The value of the parameter sent to class when you instantiate( Fancy word for create ) the object.

echo $example->helloWorld();

Conclusion

This has been a brief introduction into PHP classes. The subject of PHP’s class / OOP paradigm is very deep and would it would not be practical to cover every aspect of it in one blog post. I would highly recommend a dedicating the time to learn how powerful PHP’s OOP the capabilities have become since PHP 5. I hope this tutorial has been helpful and sparked interest in exploring PHP classes further.

best wishes,

Danny Nunez