Find » Technology » Tutorials » PHP Object Oriented Programming OOP...

PHP Object Oriented Programming OOP for Beginners

Taking a Logical Look at Using OOP in Your PHP Applications

By jeff griffiths, published Mar 28, 2007
Published Content: 1  Total Views: 0  Favorited By: 0 CPs
Embed:  
Rating: 3.0 of 5
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 class.

$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');

Comments
Type in Your Comments Below - (1000 characters left)

Submit your own content on this or any topic. Get started »
Advertisment