Could someone tell me how the "old-style" object constructor is different from the "new-style" constructor? I'm learning PHP OOP, and I want to know when I'm reading old syntax vs new syntax, and better understand how OOP has changed in PHP over time.
New Style
class aObject
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}
The "old" constructor syntax is referring to PHP4. The last release of PHP4 was in 2008, and the first release of PHP5 was in 2004. This is an example of an old-style class and a new-style class.
Old (PHP4)
<?php
class MyOldClass
{
var $foo;
function MyOldClass($foo)
{
$this->foo = $foo;
}
function notAConstructor()
{
/* ... */
}
}
New (PHP5+)
<?php
class MyNewClass
{
var $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function notAConstructor()
{
/* ... */
}
}
You'll notice a couple of things here. The most significant change is that the canonical way to name a constructor has changed from ClassName()
to __construct()
. This gives all class constructors the same, predictable name--a necessary convenience. Imagine you had a class called ParentClass
with 20 children, each with their own constructors. If you wanted to call the parent constructor from each child class, you'd call ParentClass::ParentClass()
. If you wanted to change the name of ParentClass
, you'd have to change all 20 constructor calls. But, with the new method, you'd just call parent::__construct()
, which would always work, even when the parent class's name changes.
Related to this change, PHP5 also introduced class destructors (__destruct()
), which is called when an object is destroyed (the opposite of a constructor).
Such method names begin with __
, like __construct()
, as well as __get()
, __set()
, __call()
, __isset()
, __unset()
, __toString()
, etc. are called magic methods.
PHP5 brought a lot of dramatic changes, but largely tried to maintain compatibility with PHP4 code, and thus, old-style constructors were still allowed.
PHP7, which has now been released this year, declared the old-style constructors officially deprecated (raises E_DEPRECATED
error),
PHP8 will have old style constructors removed entirely.