This tutorial is an introduction to object oriented programming (OOP) with PHP. Upon finishing this tutorial, you should have the basic tools necessary to begin navigating the world of OOP. Throughout, we will build upon one example while key terms and nuances to OOP with PHP are introduced. In addition, some time will be spent showing how to integrate object oriented PHP with MySQL.
Creating Our First Object
Not surprisingly, object oriented programming is focused around objects. While the idea of objects may be foreign to you in coding terms, understanding what objects are and why we use them shouldn't take long. In short, our non-programming world is comprised of objects. Computers, fish, clouds, people, and cars are all objects. Objects have properties like color, size, name, and speed. Objects can also be comprised of other objects: cars have doors; doors have handles; handles have plastic levers; so on and so forth. Objects are everywhere around us. For this reason, many programmers find object oriented programming relatively easy to understand.
So how do objects translate into code? If we were building a website about users, we would create one or many user objects. Objects are created using classes. Classes are groups of related variables and functions. Variables hold our object's properties like color, size, and speed. Functions perform actions like set variable values or open files. In this example, we could create user objects with a User class. You can think of the User class as a template for any user objects.
Creating an object is called instantiation (creating an instance). Let's instantiate a user object and code the corresponding User class:
/* create new object */
$cesar = new User();
/* class to create objects with */
class User
{
//Methods
}
Right now this user can't do anything and doesn't have any attributes. Within classes, we use methods (aka functions) and variables to give our objects functionality and properties. Let's redo our first example so that our users can have a name:
/* create a new object */
$cesar = new User();
/* call object methods */
$cesar->setName( 'Cesar Mancilla' );
echo $cesar->getName();
class User
{
private $name;
public function setName( $val )
{
$this->name = $val;
return;
}
public function getName()
{
return $this->name;
}
}
As you can see, methods are declared using function [methodName] format, as is standard in PHP. This simple example shows us how we can apply a name to the object, then access the name.
Subscribe to my feed