“旧”构造函数语法是指 PHP4。 PHP4 的最后一个版本是在 2008 年,PHP5 的第一个版本是在 2004 年。这是一个旧式类和一个新式类的示例。
旧版 (PHP4)
<?php
class MyOldClass
{
var $foo;
function MyOldClass($foo)
{
$this->foo = $foo;
}
function notAConstructor()
{
/* ... */
}
}
新 (PHP5+)
<?php
class MyNewClass
{
var $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function notAConstructor()
{
/* ... */
}
}
您会在这里注意到几件事。最重要的变化是命名构造函数的规范方式已从ClassName() 更改为__construct()。这为所有类构造函数提供了相同的、可预测的名称——这是必要的便利。想象一下,您有一个名为 ParentClass 的类,它有 20 个孩子,每个孩子都有自己的构造函数。如果你想从每个子类调用父构造函数,你会调用ParentClass::ParentClass()。如果您想更改 ParentClass 的名称,则必须更改所有 20 个构造函数调用。但是,使用新方法,您只需调用 parent::__construct(),它始终可以工作,即使父类的名称发生更改。
与此变化相关,PHP5 还引入了类destructors (__destruct()),在对象被销毁时调用(与构造函数相反)。
另一个关键变化是 PHP5 引入了method and property visibility,它允许对类的方法和属性进行某种“访问控制”。只有标记为public 的方法和属性才能从类或其子级之外的上下文中访问。以下是这方面的例子:
<?php
class StackOverflow
{
/* This can be accessed from anywhere.
*
* You can access it from outside the class:
* $so = new StackOverflow();
* $so->publicProperty = 10;
* echo $so->publicProperty;
*
* Or from inside the class:
* $this->publicProperty = 5;
* echo $this->publicProperty;
*/
public $publicProperty = 1;
/* This can be accessed only from methods inside this class.
*
* $this->privateProperty = 5;
* echo $this->privateProperty;
*
* You cannot access it from outside the class, as above.
* Private properties cannot be accessed from child classes,
* either.
*/
private $privateProperty = 2;
/* This can be accessed only from methods inside this class,
* OR a child-class.
*
* $this->protectedProperty = 5;
* echo $this->protectedProperty;
*
* You cannot access it from outside the class, as with public.
* You can, however, access it from a child class.
*/
protected $protectedProperty = 3;
}
现在,方法的工作方式完全相同。您可以将类中的函数(方法)标记为public、private 或protected。在 PHP4 中,所有的类成员都是隐含的public。同样,构造函数(__construct())也可以是public、private或protected!
如果一个类不包含 public 构造函数,则它不能被类之外的代码实例化(或者,它的子类,对于protected)。那么你将如何使用这样的类呢?好吧,static methods,当然:
<?php
class ClassWithPrivateConstructor
{
private $foo;
private function __construct($foo)
{
$this->foo = $foo;
}
public static function fromBar($bar)
{
$foo = do_something_to($bar);
return new self($foo);
}
}
要从其他地方实例化这个类,你可以调用:
$obj = ClassWithPrivateConstructor::fromBar($bar);
当您需要在调用构造函数之前对输入进行预处理,或者当您需要多个接受不同参数的构造函数时,这会很有用。
此方法名__construct(),以及其他以__开头的方法名,如__get()、__set()、__call()、__isset()、__unset()、__toString()等叫magic methods。
PHP5 带来了很多dramatic changes,但在很大程度上试图保持与 PHP4 代码的兼容性,因此仍然允许使用旧式构造函数。
PHP7 已于今年发布,构造函数语法没有变化。 PHP7 中与class 相关的唯一重要更改是允许使用匿名类(请参阅here)。
从 PHP7 开始,旧式构造函数 are officially deprecated(引发 E_DEPRECATED 错误),将在 PHP8 中完全删除。