In a programming environment objects can be though as "black boxes". They receive user input, do something with it and can give an output if you want to, all of this without needing to know what's happening inside.
Two important aspects of objects are their methods and their properties. Methods are a special kind of function and properties special kind of variables that reside in within an object. An example of an object will be your computer. Your computer properties nclude: operating system, speed and memory. Your computer methods include: boot, processing and shoot down.
To make an object in php you first need to define a class. A class can be thought as a template from where all objects of that class come from. Bellow is a sample declaration of a class.
|
class computer
{
// here comes the methods and properties
} |
To make an object of this class you make use of the new statement.
|
mycomputer=new computer();//this is a computer object
othercomputer=new computer();//this is another computer object |
To add properties to the class we make use of the var keyword.
|
class computer
{
var $osystem="linux"
} |
Notice that it's not necessary to include an initial value for the property. To add methods to the class we just write the function inside of it
|
class computer
{
var $osystem="linux"
function sysboot()
{
print "I´m booting";
}
} |
To access the methods and properties of the object outside it you use the -> operator. For example:
will call the sysboot method and
|
mycomputer->osystem = "windows" |
will let you change the osystem variable value.
Methods can access the properties of their object using the special variable $this like in the following example.
|
<?php
class message
{
var $mail;
var $subject;
var $text;
function sendmail()
{
mail($this->mail, $this->subject, $this->text);
}
}
$messg = new message();
$messg->sendmail();
?> |
Remember that the whole idea of working with objects is to keep related functions of your code together. For example we can continue to elaborate the above example to include an email validator function, a function to check for message and subject length and so on. If we continue to work on this class but instead add unrelated functions like a function to format a date, the code will become more difficult to read which is the opposite effect that we want to achieve.