Home / code / php

Classes PHP

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.

In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor (see below).


<?php
/* None of these will work in PHP 4. */
class Cart
{
    var $todays_date = date("Y-m-d");
    var $name = $firstname;
    var $owner = 'Fred ' . 'Jones';
    var $items = array("VCR", "TV");
}

/* This is how it should be done. */
class Cart
{
    var $todays_date;
    var $name;
    var $owner;
    var $items;

    function Cart()
    {
        $this->todays_date = date("Y-m-d");
        $this->name = $GLOBALS['firstname'];
        /* etc. . . */
    }
}
?>

 

TOP

Latest script:

 

Books: