PHP Tutorial: OOP

We have covered on the basics of PHP and its fundamental concepts. Now, let’s move on to the concept of Objected-Oriented in PHP. In this article, I’ll be covering briefly on the concept of OOP and an in-depth analysis of PHP OOP. It might sound a bit scary, but it actually isn’t that scary once you’ve grasp onto its idea.

In a nutshell, we’ll be covering the following:

  • Objects
  • Classes
  • Functions
  • Attributes
  • Visibility
  • Extension
  • Implementation

Object Oriented Programming

OO-What? That’s right, OOP. OOP isn’t just unique to PHP; lots of programming languages have OO concepts implemented – Java, Javascript, Python, C#, etc. The OO concept in programming is essentially treating data as objects that can be passed around easily, controlled with visibility and accessed easily. Objects are constructed through calling its class file. In a way, the class file is the master and the objects are the replica of its master. These objects, well, contains the data that we’ve gave it on initialization or through its class. In some ways, it is like an array but with functions and visibility control.

objects

PHP OOP

The following topics will include elaborations and examples of various OO topics in PHP. Without further ado, let’s jump right into it! :)

Classes

As mentioned above, in order to instantiate an object, there must be a class to instantiate from. A class is simply a collection of attributes (variables) and operations (functions/methods). Sounds a little confusing?

Fear not, let’s continue from this part with an example of a Shopping Cart class.

<?php
class Cart
{
	function addItem($item)
	{
	}
}

$cart = new Cart(); // instantiate the cart object
?>

So here are some assumptions:

  • There is another class named Item

Right above here, we’ve done some magic, let’s just say that $cart is an instance of the class, Cart, and that $cart is an object that we have instantiated. And that’s our basic cart class! Simple, isn’t it? Oh and, inside the class, there’s a function named “addItem”.

Functions?

By now, you might be wondering, “What are functions???”. Functions, or methods, are things that can be called upon to carry out certain actions you might wanna do. Let me elaborate further with an example:

<?php
function addItem($item)
{
	if($item == null)
	{
		return "Item does not exist!";
	}
	else
	{
		// Do the adding of item into cart
	}
}


$random_item = null; // Initialise the item object
$result = addItem($random_item); // Now let's call the function

echo $result; // Will output "Item does not exist!"

?>

We pass in variables into the function, “addItem”. And in this particular function, we have a parameter named $item. Once the function is called with the supplied parameter, it will be able to use the variable passed in.

Surprised? Yep, it’s really just that. It’s your typical normal PHP stuff! Just that we wanna put it into a function so that repetitive tasks can be carried out easily through calls. :)

Function in a class

Now, let’s combine what we’ve learn so far into a single class again. We’ll also do a really quick demonstration of calling a function that is within the class.

<?php
class Cart
{
	function addItem($item)
	{
		if($item == null)
		{
			return "Item does not exist!";
		}
		else
		{
			// Do the adding of item into cart
		}
	}
}

$item = null; // Initialise the item object
$cart = new Cart(); // instantiate the cart object
$result = $cart->addItem($item); // Now let's call the function

echo $result; // Will output "Item does not exist!"
?>

WAIT WHAT?! What’s the “->” thing? Well, it might look a little familiar because arrays uses “=>” but, “->” and “=>” are different things. In a way, “->” is used for “seeking into” and looking for the particular attribute or operation.

And that’s pretty much how we’re gonna call our function with the object that we have instantiated.

Attributes

Attributes are the variables that exists inside the Class. It is mainly used for storing data in the object so that it can be passed around easily. Let’s continue from here with an example:

<?php
class Cart
{
	public $id;
}

$cart = new Cart(); // instantiate the cart object
$cart->id = 1; // We set the id to 1

$cart_2 = new Cart(); // instantiate the cart object
$cart_2->id = 2; // We set the id to 2

echo $cart->id; // This will output "1"
echo $cart_2->id; // This will output "2"
?>

The “public” is the visibility of the attribute, hold your horses, we’ll touch on that later on but for now, let’s focus on the class and attribute. Similarly to how the functions are being called, for our attributes, we use “->” to get or set its values. By right (but not necessarily), we should have a get and set method created for our attributes, but we will correct that later under “Visibility” topic.

Constructors & Destructors

Let’s get on with constructors first. Constructors are basically functions that will be called upon instantiating the object. Let me demonstrate this to you with an example:

<?php
class Cart
{
	public $id;

	function __construct()
	{
		// A default empty constructor
	}

	function __construct($id)
	{
		// A constructor with an $id parameter
		$this->id = $id; // Set the ID
	}
}

$cart = new Cart(); // instantiate the cart object

$cart_2 = new Cart(2); // instantiate the cart object with a parameter

echo $cart->id; // This will output null
echo $cart_2->id; // This will output "2"
?>

Wow, it’s really that simple. As for de-constructors, or simply destructors, they are called when there are no other references to the particular object we have instantiated or when a “shutdown” of the PHP script is called.

<?php
class Cart
{
	public $id;

	function __construct()
	{
		// A default empty constructor
	}

	function __construct($id)
	{
		// A constructor with an $id parameter
		$this->id = $id; // Set the ID
	}

	function __destruct() 
	{
		echo "Destroying " . $this->id . "\n";
	}
}

$cart = new Cart(1); // instantiate the cart object

echo $cart->id; // This will output 1

// now it will output "destroying 1"

echo "blah blah blah"; // and then output blah blah blah

?>

And that’s it for constructors and destructors.

Visibility

As for visibility, it is what is visible to who. There are 3 main types of visibility types – public, protected and private.

For public, everyone (other classes, other files) can access it without any issues. For protected, only its children (we’ll talk more about this under “Extension”) and the object itself, can access it. For private, only the object itself can access it.

<?php
class Cart
{
	private $id; // Let's make it private and create our get and set functions

	public function set_id($id)
	{
		// Let's do some validation
		if(is_int($id))
		{
			$this->id = $id; // Allow setting only if the ID is an integer
		}
	}

	public function get_id()
	{
		return $this->id;
	}
}

$cart = new Cart(); // instantiate the cart object
$cart->id = 1; // This cannot be done!

$cart_2 = new Cart(); // instantiate the cart object
$cart_2->set_id(2); // We set the id to 2

echo $cart->id; // This will generate error
echo $cart_2->id; // This will generate error
echo $cart_2->get_id(); // This will output "2"
?>

We have set functions for us to validate information before setting them and in this case, we wanna make sure that the $id is an integer. The get function allows the “public” to retrieve attribute information that are protected or private. That’s pretty much for visibility, except we have yet to touch on “protected”.

Extension

Extension, in its formal terms, is called sub-class or children. It is an extension of its super-class or parent class. It inherits whatever attributes or methods its parent has. Let’s continue with an example:

<?php
class Cart
{
	private $id; // Let's make it private and create our get and set functions

	protected function set_id($id) // Only the children, Trolley, can set it.
	{
		// Let's do some validation
		if(is_int($id))
		{
			$this->id = $id; // Allow setting only if the ID is an integer
		}
	}

	public function get_id()
	{
		return $this->id;
	}
}

class Trolley extends Cart
{
	private $wheels;

	public function set_parent_id($id)
	{
		parent::set_id($id);
	}
}

$trolley = new Trolley(); // instantiate the trolley object
$trolley->set_parent_id(1); // We set the id to 1

$cart = new Cart(); // instantiate the cart object
$cart->set_id(2); // Not possible, only child can do it as it is protected!

echo $trolley->get_id(); // This will output "1"
?>

That’s pretty much what I meant by inheritance. Simple, isn’t it? :)

Let’s move on to a slightly more complex topic – implementation.

Implementation

Implementation, also known as abstract classes, are class implementations of interface templates. I know it might sound a little complicated but not to worry, here’s an example to help you understand:

<?php
interface CartInterface
{
	public function set_id($id);
	public function get_id();
}

class Cart implements CartInterface
{
	private $id; // Let's make it private and create our get and set functions

	public function set_id($id)
	{
		// Let's do some validation
		if(is_int($id))
		{
			$this->id = $id; // Allow setting only if the ID is an integer
		}
	}

	public function get_id()
	{
		return $this->id;
	}
}

$cart = new Cart(); // instantiate the cart object
$cart->set_id(2); // set the ID to 2

echo $cart->get_id(); // This will output "2"
?>

In a nutshell, whatever attributes and methods the interface has, the classes that implements the respective interface must also have those attributes and methods included. The signature (the visibility) and its parameters (values passed in) must be the same as its interface. If the interface has a public function, the class implementation must have the public function implemented.

Conclusion

That’s it for PHP OOP! It wasn’t that difficult, wasn’t it? :) Hope you’ve enjoyed learning PHP so far. If you have any questions, feel free to shoot them in the comments section below.

Next Tutorial: Not Available Yet

Tutorial Overview: Fast Track Learning

Author: Woo Huiren

Currently a student at National University of Singapore. I contribute to opensource projects - primarily PHP and Angular related. I write about PCF and PWS related stuff too.

Leave a Reply