Posted by Toby A Inkster on 02/27/07 09:11
Daz wrote:
> I am wondering why constructors are different in PHP5.
Under PHP 4:
<?php
class A
{
function A ()
{
print "Constructor called\n";
}
}
class B extends A
{
// The constructor for this class is now a
// function called 'A'. If you were reading the
// code, this might be somewhat confusing, but
// you could logically infer that it's because
// it extends A.
}
class C extends B
{
// The constructor for this class is now a
// function called 'A'. There is no clue within
// this class definition as to why that is! If
// classes A and B were defined in a separate
// file, then there would be no clues in this
// file that the constructor function is called
// 'A'.
}
class D extends C
{
function D ()
{
print "This is D!\n";
parent::C(); // wrong!
}
}
?>
PHP 5 allows all classes to have the same name for their constructor. So
when subclassing an existing class, you can reliably call the parent's
constructor function as "parent::__contruct()" without having to look into
the internals of the class that you're extending. (Which is how it should
be with OO programming: classes should be black boxes.)
--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux
* = I'm getting there!
[Back to original message]
|