PHP Object Oriented Programming OOP for Beginners
Taking a Logical Look at Using OOP in Your PHP Applications
Embed:
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');

You may also like...
- PHP: Getting Text to Display from ODBC D...
- How to Customize PHP Flag Settings Witho...
- Introduction to PHP 5 and SimpleXML
- Computer Programming - Then and Now
- How to Make a PHP Hit Counter
- How to Produce Good and Resource-friendl...
- The Best Approach to Learning Computer P...
- The Best Computer Programming Language f...
- Adults Only Family Programming on FOX
- A Short Introduction to Java Programming...
Comments
Type in Your Comments Below - (1000 characters left)
Today's Most Commented On
Advertisment