Hey Rowan,
> On 17 Jan 2015, at 19:40, Rowan Collins <[email protected]> wrote:
>
> On 17/01/2015 18:33, Todd Ruth wrote:
>>> As already mentioned I think as an end result we shouldn't have two
>>> >ways to define constructors. Given that PHP already prefers the
>>> >new-style constructors I've proposed that we work towards dropping the
>>> >old-style, it's just down to a matter of how.
>> I've been following these threads for about 10 years and beg that php
>> internals continues to "live and let live".
>> There have been many, many threads over the years from what I would call
>> (with obvious bias) "OO fundamentalists". They seem to be at war with
>> code that is "bad form".
>
> This is an argument that comes up a lot, and it has some merit, sometimes.
>
> I don't think using __construct over named-method for constructors really has anything to
> do with "OOP fundamentalism"; it was a design change to make certain things simpler (like
> parent::__construct), and more consistent (all reserved magic methods begin with __, so any method
> not beginning with that is safe to use however you like).
To add on to what you said, there’s also a quite important benefit that __construct is a lot more
obvious in what it does.
Looking at the following code:
class Foo {
public $foo,
$bar,
$qux;
public function foobar() {
// ...
}
public function bar() {
// ...
}
public function foo() {
// ...
}
public function baz() {
// ...
}
public function qux() {
// ...
}
}
It’s not easy to spot the constructor at a glance, and it’s very easy to miss.
Compare that to the following:
class Foo {
public $foo,
$bar,
$qux;
public function foobar() {
// ...
}
public function bar() {
// ...
}
public function __construct() {
// ...
}
public function baz() {
// ...
}
public function qux() {
// ...
}
}
Far more obvious. This actually tripped me up on more than one occasion when updating tests broken
by the removal of PHP 4 constructors in php-src. Sure, the constructor should probably be the first
method, but *even if it is* it’s still nowhere near as obvious in PHP 4 style.
Similarly, what does the following do?
$this->foo();
It looks like a normal method call, and it is in a sense. But if you’re in Bar and inheriting from
Foo, that’s a call to the parent class’s constructor!
The following is much more obvious:
parent::__construct();
I think it’s pretty clear why we changed to PHP5-style constructors. They’re just a lot more
recognisable. :)
--
Andrea Faulds
http://ajf.me/