Created
March 14, 2011 02:06
-
-
Save LeviSchuck/868659 to your computer and use it in GitHub Desktop.
main.php of PHP OOP Tutorial 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Object Oriented Programming in PHP Intro #2 | |
class bank { | |
private $name = ''; | |
public function __construct($name) { | |
echo "Starting the bank: $name."; | |
$this->name=$name; | |
} | |
public function iHaveThisMuchMoney(){ | |
$sum = 0; | |
foreach($this->accounts as $account){ | |
if($account instanceof account){ | |
$sum += $account->getMoney(); | |
} | |
} | |
return $sum; | |
} | |
private $accounts = array(); | |
private $special = array(); | |
public function addAccount(account $account){ | |
if($account instanceof account){ | |
$this->accounts[] = $account; | |
} | |
if($account instanceof specialAccount){ | |
$this->special[] = $account; | |
} | |
} | |
public function prefered($account){ | |
return in_array($account, $this->special); | |
} | |
public function getAccountFromID($id){ | |
foreach($this->accounts as $account){ | |
if($account instanceof account){ | |
if($account->myID()==$id){ | |
return $account; | |
} | |
} | |
} | |
return null;//Sorry, not in mah bank. | |
} | |
} | |
class account { | |
private static $instanceID = 0; | |
private $id = -1; | |
public function __construct() { | |
$this->id=self::$instanceID; | |
self::$instanceID+=1;//Prepare the next ID for the next account | |
} | |
private $money = 0; | |
public function deposit($moneys){ | |
$this->money = $moneys; | |
} | |
public function withdraw($money){ | |
if($money <= $this->money){ | |
$this->money -=$money; | |
return true; | |
} | |
return false; | |
} | |
public function getMoney(){ | |
return $this->money; | |
} | |
public function myID(){ | |
return $this->id; | |
} | |
} | |
class specialAccount extends account { | |
} | |
$bank = new bank('Toad'); | |
echo "\n"; | |
echo "I have this much money: ".$bank->iHaveThisMuchMoney()."\n"; | |
$acc1 = new account(); | |
$acc1->deposit(42.13); | |
echo "some new account has ".$acc1->getMoney()."\n"; | |
$acc2 = new account(); | |
$acc2->deposit(13.42); | |
$acc3 = new specialAccount(); | |
$acc3->deposit(22.22); | |
$bank->addAccount($acc1); | |
$bank->addAccount($acc2); | |
$bank->addAccount($acc3); | |
echo "I have this much money: ".$bank->iHaveThisMuchMoney()."\n"; | |
echo "Is account 3 a prefered customer? ".(int)$bank->prefered($bank->getAccountFromID(1)); | |
echo "\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment