It is important to note that in procedural programming, the functions and the data are separated from one another. In OO programming, data and the functions to manipulate the data are tied together in objects. Objects contain both data (called attributes or properties) and functions to manipulate that data (called methods). An object is defined by the class of which it is an instance. A class defines the attributes that an object has, as well as the methods it may employ. You create an object by instantiating a class. Instantiation creates a new object, initializes all its attributes, and calls its constructor, which is a function that performs any setup operations. A class constructor in PHP5 should be named __constructor() so that the engine knows how to identify it. The following example creates a simple class named User, instantiates it, and calls its two methods: <?php
class User {
public $name;
public $birthday;
public function __construct($name, $birthday)
{
$this->name = $name;
$this->birthday = $birthday;
}
public function hello()
{
return "Hello $this->name!\n";
}
public function goodbye()
{
return "Goodbye $this->name!\n";
}
public function age() {
$ts = strtotime($this->birthday);
if($ts === -1) {
return "Unknown";
}
else {
$diff = time() - $ts;
return floor($diff/(24*60*60*365)) ;
}
}
}
$user = new User('george', '10 Oct 1973');
echo $user->hello();
echo "You are ".$user->age()." years old.\n";
echo $user->goodbye();
?>
Running this causes the following to appear: Hello george! You are 29 years old. Goodbye george! The constructor in this example is extremely basic; it only initializes two attributes, name and birthday. The methods are also simple. Notice that $this is automatically created inside the class methods, and it represents the User object. To access a property or method, you use the -> notation. On the surface, an object doesn't seem too different from an associative array and a collection of functions that act on it. There are some important additional properties, though, as described in the following sections:
blog comments powered by Disqus |