Account Class
PHP Code Examples
[Download]
<?php

// Get some class!  (Maybe you can let me have some extra.)
class Account {
	// Array of accounts.
	private $accnts = array();

	// Constructor creates all accounts with initial balances.  PHP 4
	// used C++-style constructors named after the class.
	//   Create with new Account(name1, amt1, name2, amt2, ...)
	function __construct($accnts) {
		// Check that the account list is well-formed.
		$size = count($accnts);
		if($size % 2 == 1) {
			$accnts = array_merge($accnts, array(0));
			++$size;
		}

		// This essentially copies the input account list to the
		// account list, but it stops if the list is not well-formed.
		$this->accnts = array();
		foreach($accnts as $name => $val) {
			if(!is_string($name) || !is_int($val) || $val < 0)
				break;
			$this->accnts[$name] = $val;
		}
	}

	// Transfer accounts.
	function xfer($from, $to, $amt)
	{
		// Check and transfer.
		if(! array_key_exists($from, $this->accnts) ||
				! array_key_exists($to, $this->accnts))
			return 0;
		if($this->accnts[$from] < $amt)
			return 0;

		$this->accnts[$from] -= $amt;
		$this->accnts[$to] += $amt;

		return 1;
	}

	// Find out how much is there.
	function bal($name)
	{
		if(! array_key_exists($name, $this->accnts)) return -1;
		return $this->accnts[$name];
	}

	// Get the list of account names.
	function names()
	{
		return array_keys($this->accnts);
	}

	// Print out the accounts
	function pr($targs = "", 
		    $karg = 'style="text-align: right; padding-left: 10pt;"', 
		    $darg = 'style="text-align: left;"')
	{
		$keys = $this->names();
		sort($keys);

		echo "<table $targs>";
		foreach ($keys as $k) {
			echo "<tr><td $karg>$k:</td><td $darg>",
				$this->accnts[$k], "</td></tr>";
		}
		echo "</table>";
	}
}

?>