Example of OOP :: Currency Converter

<?php //Created By Peter DeMartini on 4/10/12 as an example of OOP //Enjoy :) //A simple utility class class Utility { //Outputs message to browser using HTML public function outputToBrowser($msg){ //If object or array use var_export //else use echo if(is_array($msg) || is_object($msg)){ echo "<pre>"; var_export($msg, true); echo "</pre>"; }else{ echo $msg; } //Add line break for readability echo "<br />"; } } //This Object has the ability to convert a number into currency format class currencyConverter extends Utility{ //Assign object attributes var $input; var $output; var $sign = '$'; //Validate Number (Throw error if not numeric) function __construct($input) { if(!is_numeric($input) && !is_float($input)){ throw new Exception("Inputed number is not numeric."); } $this->input = $input; } //Output thank you respnse on object deconstruction function __destruct() { parent::outputToBrowser('Thank you for using Currency Converter'); } //Convert Object public function convert(){ //input $input = $this->input; //call private function to convert number $input = $this->_convertToCurrency($input); //set output to new value $this->output = $input; } //Output Input and Output values public function output(){ parent::outputToBrowser("<strong>Old Value</strong> :: " . $this->input); parent::outputToBrowser("<strong>New Value</strong> :: " . $this->output); } //return converterd value public function getConverted(){ return $this->output; } public function convertAndGet(){ //input $input = $this->input; //call private function to convert number $input = $this->_convertToCurrency($input); //set output to new value return $this->output = $input; } //Restore output value back to the starting value public function restore(){ $this->output = $this->input; } //Private function convert currency using PHP's function number_format() private function _convertToCurrency($input){ //convert number to currency return $this->sign . number_format($input, 2, '.', ','); } } //Test Currency Converter //Instantiate Object $converter = new currencyConverter(5211231230.1242); //convert number to currency $converter->convert(); $converter->output(); //restore back to original number $converter->restore(); $converter->output(); ?>

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.