Chapter 13. Classes and Objects

Table of Contents
class

class

A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:

<?php
class Cart {
    var $items;  // Items in our shopping cart
   
    // Add $num articles of $artnr to the cart
 
    function add_item ($artnr, $num) {
        $this->items[$artnr] += $num;
    }
   
    // Take $num articles of $artnr out of the cart
 
    function remove_item ($artnr, $num) {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } else {
            return false;
        }   
    }
}
?>
     

This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.

Note: In PHP 4, only constant initializers for var variables are allowed. Use constructors for non-constant initializers.

Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.

 $cart = new Cart;
 $cart->add_item("10", 1);
    

This creates an object $cart of the class Cart. The function add_item() of that object is being called to add 1 item of article number 10 to the cart.

Classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class and what you add in the extended definition. This is done using the extends keyword. Multiple inheritance is not supported.

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

This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). Yo