extends

Often you need classes with similar variables and functions to another existing class. In fact, it is good practice to define a generic class which can be used in all your projects and adapt this class for the needs of each of your specific projects. To facilitate this, Classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class (this is called 'inheritance' despite the fact that nobody died) and what you add in the extended definition. It is not possible to substract from a class, that is, to undefine any existing functions or variables. An extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.


class Named_Cart extends Cart {
    var $owner;
  
    function set_owner ($name) {
        $this->owner = $name;
    }
}
    

この例は、Cart の全ての変数及び関数に加えて変数 $owner と 関数 set_owner() を保持するクラス Named_Cart を定義しています。 この定義により、名前付きの籠を通常の手段で作成し、籠の保有者を 設定したり得たりすることができます。 名前付きの籠で元の籠クラスの関数を使うことも可能です。


$ncart = new Named_Cart;    // 名前付きの籠を作成
$ncart->set_owner ("kris"); // 籠の所有者の名前を設定
print $ncart->owner;        // 籠の所有者を出力
$ncart->add_item ("10", 1); // (籠から継承された機能)