By using this site you agree to the use of cookies and related technologies.

Learn more

PHP Object Oriented Programming Tutorial

Beginners Tutorial in Object-oriented programming in PHP.

Edited: 2016-09-24 03:22

This tutorial aim to explain the basics of Object-oriented PHP. We will briefly cover how to use classes and objects so that you will hopefully understand what they are, and how to use OOP in real situations.

One reason why it's good to use OOP rather than just basic functions, is to avoid conflicting code. If you had a lot of functions the chance that function names would at some point overlap would be rather high. This is avoided entirely with OOP, and you can easily implement code (libraries) written by other developers, without having to worry about these conflicts.

OOP is about maintainability and scalability, and makes it easier to maintain larger projects and to reuse code in other files and projects. It might also make your code cleaner, and encourage you to write code that is easier to read and understand.

Classes and Objects in PHP

A class is a template used to create objects. Classes can include Properties and Methods (variables and functions), which can be reached from other functions within the class, and even from outside the class, depending on their configuration.

For instance, variables inside the class can either be declared as public or protected. Public variables can be accessed from everywhere, and protected can only be accessed from within the class itself, and by classes that inherits them.

If properties (variables) are declared using the private keyword, then the properties will only be accessible from within the class that created them.

OOP PHP Properties Example

The below is a simple PHP class, containing two variables.

class MyClassName {
 public $Property1 = 'Hallo hallo!';
 public $MyVariableName = 'Hallo dude!'; // Another Property
}

To access these variables, we first need to create an object, which is basically just en instance of the class.

$MyObject = new MyClassName(); // Creates an object from the class

We can then output or change the variable values as we wish.

echo $MyObject->Property1 ."<br>";
$MyObject->MyVariableName = 'My House'; // Changes the variable value

OOP PHP Methods Example

You can also include functions in your classes, when this is done the functions are referred to as methods. A simple method that everyone should be able to understand is shown below.

class MyClassName {
 function SayHallo() {
   return 'Hallo';
 }
}

$MyObject = new MyClassName();
echo $MyObject->SayHallo();