PHP Object Oriented Programming OOP for Beginners
Taking a Logical Look at Using OOP in Your PHP Applications
PHP is quickly becoming one of the web's most popular programming languages, and for good reason. As of PHP 4.0, PHP has supported what is known as Object Oriented Programming (OOP).To start, we'll take a look at what makes up an object.
Objects in PHP are instantiated (created, used) by making a call to a
$user = new User();
In this case, $user becomes the object, and the class User is used as a template. More on this below.
The class being called contains variables, which are referred to as properties in the world of OOP. The class also contains functions, referred to as methods in OOP.
In this case, we aren't telling PHP to actually create a new user. We are simply telling PHP that the variable $user will contain the variables (properties) and functions (methods) which are defined in the actual class. Typically, each class is stored in it's own file to increase modularity. In this case, the user class may be stored in lib/User.class.php. The code to instantiate (create, use) an object of this class would look like the following.
require_once('lib/User.class.php');
$user = new User();
So, basically, the class is the template and the object is one instance of this template. In this case, User.class.php is the class and $user is the object. Before we go any further, let's take a look at what this class might look like. Note that what immediately follows the word class is the class name and is used to instantiate (create, use) an object of this class.
class User
{
var $id;
var $name;
var $address;
function setName($name)
{
$this->name = $name;
}
}
Right now you're probably saying to yourself, what is $this? I don't see it defined anywhere. $this in PHP is used to refer to the current object (current instance of that class). The following example will clarify this further.
require_once('lib/User.class.php');
$user = new User();
$user->setName('Joe Smith');
Related information
Most Comments Today
- Oh No! Michael Jackson's Body and Brain Missing Is Michael Jackson's body and brain missing? According to many websites they... 33 Comments
- Michael Jackson is Missing The casket is missing, where is it? How did it disappear? 32 Comments
- Real Estate: Renting Your Home and Bad Tenants If you decide to rent out your home, do a thorough reference check with previ... 28 Comments
- Hot News Quickies - Thursday, July 9, 2009 News happens while you sleep - get your Hot News Quickies here! 28 Comments
- Every Day Heroes At every disaster, in every community, when people are hurting who are the fi... 25 Comments
- Sarah Palin 2012? Sarah Palin 2012? 25 Comments





