技术开发 频道

PHP开发经典教程 (Part7):面向对象编程

构造器与构造器函数 

    当调用类来创建新的对象时,自动执行类的一个函数也是可能的。用技客的行话来讲,此被称为构造器,且为了使用它,你的PHP 5类定义必须包含一个特殊的函数:_construct()。 

    举例而言,如果你想让所有新生的熊是褐色而且体重为100个单位,那么你可以将这些添加到你的类定义中:

<?php // PHP 5 // class definition class Bear { // define properties public $name; public $weight; public $age; public $colour; // constructor public function __construct() { $this->age = 0; $this->weight = 100; $this->colour = "brown"; } // define methods } ?>

 
    在PHP 4中,你的构造器必须和类拥有同样的名称。下面为PHP 4写的同样的代码:

<?php // PHP 4 // class definition class Bear { // define properties var $name; var $weight; var $age; var $colour; // constructor function Bear() { $this->age = 0; $this->weight = 100; $this->colour = "brown"; } // define methods } ?>

 

    现在,试试创建和使用类的实例:

<?php // create instance $baby = new Bear; $baby->name = "Baby Bear"; echo $baby->name." is ".$baby->colour." and weighs ".$baby->weight." units at birth"; ?>

    这里,构造器在类的对象每次实例化时自动设置缺省属性。因此,当你运行上述脚本时,你会看到下面的结果:

Baby Bear is brown and weighs 100 units at birth

 

0
相关文章