Prev | Current Page 250 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


Constructors
You often want to initialize certain fields and even trigger the execution of methods
found when an object is newly instantiated. There??™s nothing wrong with doing so
immediately after instantiation, but it would be easier if this were done for you automatically.
Such a mechanism exists in OOP, known as a constructor. Quite simply, a
constructor is defined as a block of code that automatically executes at the time of
object instantiation. OOP constructors offer a number of advantages:
??? Constructors can accept parameters, which are assigned to specific object
fields at creation time.
??? Constructors can call class methods or other functions.
??? Class constructors can call on other constructors, including those from the
class parent.
This section reviews how all of these advantages work with PHP 5??™s improved
constructor functionality.
CHAPTER 6 ?–  O BJECT-ORIENTED PHP 183
?– Note PHP 4 also offered class constructors, but it used a different more cumbersome syntax than
that used in version 5. Version 4 constructors were simply class methods of the same name as the class
they represented. Such a convention made it tedious to rename a class. The new constructor-naming
convention resolves these issues. For reasons of compatibility, however, if a class is found to not contain
a constructor satisfying the new naming convention, that class will then be searched for a method
bearing the same name as the class; if located, this method is considered the constructor.


Pages:
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262