Prev | Current Page 252 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

If you know that
such methods should be called whenever a new object is instantiated, you??™re far better
off automating the calls via the constructor than attempting to manually call them
yourself.
Additionally, if you would like to make sure that these methods are called only via the
constructor, you should set their scope to private, ensuring that they cannot be
directly called by the object or by a subclass.
Invoking Parent Constructors
PHP does not automatically call the parent constructor; you must call it explicitly
using the parent keyword. An example follows:
CHAPTER 6 ?–  O BJECT-ORIENTED PHP 185
class Employee
{
protected $name;
protected $title;
function __construct()
{
echo "

Staff constructor called!

";
}
}
class Manager extends Employee
{
function __construct()
{
parent::__construct();
echo "

Manager constructor called!

";
}
}
$employee = new Manager();
?>
This results in the following:
Employee constructor called!
Manager constructor called!
Neglecting to include the call to parent::__construct() results in the invocation of
only the Manager constructor, like this:
Manager constructor called!
186 CHAPTER 6 ?–  O BJECT-ORIENTED PHP
Invoking Unrelated Constructors
You can invoke class constructors that don??™t have any relation to the instantiated
object simply by prefacing __constructor with the class name, like so:
classname::__construct()
As an example, assume that the Manager and Employee classes used in the previous
example bear no hierarchical relationship; instead, they are simply two classes located
within the same library.


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