Prev | Current Page 358 | Next

Rob Allen, Nick Lo, and Steven Brown

"Zend Framework in Action"

50
An object is a runtime instantiation of a class. This means that it has a name and is created using the new
keyword:
$rob = new ZFiA_Person();
The variable $rob is an object and it follows that you can have many objects of the same type. For
instance, I can create a $nick object using the same syntax:
$nick = new ZFiA_Person();
I now have two objects that are of the same class. That is, you only have one class, but can have many
instance objects of it.
Constructing and destructing
Usually an object needs to set up its internal state; that is, set the initial values of its member variables. To do
this, a special function, called a constructor is used, which has the name __construct(). This function is
called automatically when a new object is instantiated. It is very common for a class to have a contructor and
usually one or more function parameters are used in order to set the object??™s internal state. This is shown in
listing 17.2.
At the opposite end of the object??™s lifetime, another function is called, __destruct(), just as the object
is about to be deleted. This function is called the destructor and is rarely used in PHP scripts intended for the
web due to the ???set-up and tear-down every request??? nature of PHP.
Figure 17.2 Adding a constructor
class ZFiA_Person
{
private $_firstName; 1
private $_lastName; 1
public __construct($firstName, $lastName) 2
{
$this->_firstName = $firstName; 3
$this->_lastName = $lastName; 3
}
}
1 Member variables, only visible to this class
2 Constructor function
3 Assign function parameters to member variables
Listing 17.


Pages:
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
mapy polski Golec uOrkiestra 3 mieszkanie sosnowiec wokar certyfikaty energetyczne poznań