Solved

procedural conversion code:  I want a method with a try catch block in an existing class

Posted on 2013-11-22
3
290 Views
Last Modified: 2013-11-24
given one parameter at a time
6'0"
5'10"
5'10"
5'8"

want an object oriented method to return inches (IN INT; NO OTHER CHARACTERS)
72
70
70
68



<?php // RAY_temp_rgb192.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28296225.html

$height = <<<EOD
5'8"
EOD;

// TURN OFF STRICT ERROR REPORTING
error_reporting(~E_STRICT);

// COMPUTE HEIGHT IN INCHES
$inches = current(explode("'", $height)) * 12 + end(explode("'", rtrim(trim($height), '"')));

// SHOW THE WORK PRODUCT
var_dump($height, $inches);

Open in new window



I want to add a method that takes 1 parameter (height feet and inches and other characters) and returns height (INT) to an existing class.
I want this method to also have a try catch block similar to this

	public function ConvertDateTime($date_time_str = 'now')
	{
		// remove unwanted characters
		$date_time_str = str_replace('(', NULL, $date_time_str);
		$date_time_str = str_replace(')', NULL, $date_time_str);

		// translate to US English date format like 'hour', 'now', etc.
		$date_time_str = str_replace('hr', 'hour', $date_time_str);
		$date_time_str = str_replace('just now', 'now', $date_time_str);

		$date_format = NULL;
		try
		{
			$datetime = date_create($date_time_str);
			$date_format = date_format($datetime, 'Y-m-d H:i:s');
		}
		catch (Exception $e)
		{
			$this->writeLog($e->getMessage(), TRUE);
		}

		return $date_format;
	}

Open in new window

0
Comment
Question by:rgb192
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39668893
I'll try to give you an example based on your test numbers in a moment.

Here is my teaching example:
http://www.laprbass.com/RAY_try_throw_catch.php?q=0
http://www.laprbass.com/RAY_try_throw_catch.php?q=1
http://www.laprbass.com/RAY_try_throw_catch.php?q=2
http://www.laprbass.com/RAY_try_throw_catch.php?q=3

<?php // RAY_try_throw_catch.php
error_reporting(E_ALL);
echo "<pre>";

// DEMONSTRATE A TRY WITH MULTIPLE CATCH BLOCKS
// EXAMPLE: RAY_try_throw_catch.php?q=1
// http://php.net/manual/en/reserved.exceptions.php
// http://php.net/manual/en/language.exceptions.php
// http://php.net/manual/en/language.exceptions.extending.php

Class ScrewUP
{
    // CONSTRUCTOR SETS A CODE PROPERTY FOR THE OBJECT
    public function __construct($q)
    {
        // CHOOSE AN INTEGER VALUE FROM ZERO TO THREE
        $this->code = 0;
        if (!empty($q)) $this->code = floor($q % 4);
    }

    // THIS WILL THROW SOME KIND OF EXCEPTION BASED ON THE CODE
    public function hiccup()
    {
        // THESE EXCEPTIONS WILL BE CAUGHT
        if ($this->code == 0) throw new Exception_zero('Hello');
        if ($this->code == 1) throw new Exception_one('World');

        // THIS WILL BE AN UNCAUGHT EXCEPTION: FATAL ERROR
        if ($this->code == 2) throw new Exception_two('Foobar');

        // THIS WILL BE AN UNEXTENDED EXCEPTION
        throw new Exception('Naked');
    }
}

Class Exception_Zero extends Exception
{
    public function __construct($x)
    {
        parent::__construct();
        echo "Exception Zero: $x ";
    }
}

Class Exception_One extends Exception
{
    public function __construct($x)
    {
        parent::__construct();
        echo "Exception One: $x ";
    }
}

// INSTANTIATE THE CLASS USING THE URL q= VARIABLE
$x = new Screwup($_GET['q']);

// RUN THE TRY/CATCH LOGIC TO THROW AN EXCEPTION
try
{
    $x->hiccup();
}
catch (exception_One $e)
{
    echo "I Have Caught Exception Number: $x->code ";
    var_dump($e);
}
catch (exception_Zero $e)
{
    echo "I Have Caught Exception Number Zero ";
    var_dump($e);
}
catch (exception $e)
{
    echo "I Have Caught an UnExtended Exception ";
    var_dump($e);
}

Open in new window

0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39669007
Please see http://www.laprbass.com/RAY_temp_rgb192.php

This process converts the height in feet and inches into a height in inches.  Its computations are fairly obvious.  There can be one of three exceptions thrown by the Thing constructor.  There are catch() blocks for each of them.

<?php // RAY_temp_rgb192.php
error_reporting(E_ALL);

/**
 * http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28301340.html
 * want an object oriented method to return inches (IN INT; NO OTHER CHARACTERS)
 * 72
 * 70
 * 70
 * 68
 */

$params = <<<ENDPARAMS
6'0"
5'10"
5'10"
5'8"
Gooseball
62"
6'4"
ENDPARAMS;

Class Thing
{
    public function __construct($param)
    {
        // SET A DEFAULT VALUE FOR THE CLASS PROPERTY
        $this->inches = 'NOT KNOWN';

        // SPECIAL CHARACTERS REQUIRED IN THE INPUT
        $quot = '"';
        $apos = "'";

        // VERIFY THE PRESENCE OF THE SPECIAL CHARACTERS
        if (!strpos($param, $quot)) throw new QuoteException($param);
        if (!strpos($param, $apos)) throw new ApostropheException($param);

        // COMPUTE HEIGHT IN INCHES
        $param = rtrim($param, $quot);
        $array = explode($apos, $param);
        $value = 12*$array[0]+$array[1];

        // IF THERE IS A SHORT PERSON
        if ($value < 70) throw new ShortException($param);

        // IF NO EXCEPTIONS, SET THE HEIGHT AS A CLASS PROPERTY
        $this->inches = $value;
    }

    public function __toString()
    {
        return (string)$this->inches;
    }
}

Class QuoteException extends Exception
{
    public function __construct($param)
    {
        echo PHP_EOL . "$param IS MISSING A QUOTE" . PHP_EOL;
    }
}
Class ApostropheException extends Exception
{
    public function __construct($param)
    {
        echo PHP_EOL . "$param IS MISSING AN APOSTROPHE" . PHP_EOL;
    }
}
Class ShortException extends Exception
{
    public function __construct($param)
    {
        echo PHP_EOL . "$param IS TOO SHORT" . PHP_EOL;
    }
}

// MAKE AN ARRAY OF THE PARAMS
$arr = explode(PHP_EOL, $params);

// PROCESS THEM ONE-BY-ONE
echo '<pre>';
foreach ($arr as $height)
{
    echo "<h2>TRYING $height</h2>";
    try
    {
        $val = new thing($height);
    }
    catch (QuoteException $e)
    {
        var_dump($e);
        $val = 'UNKNOWN';
    }
    catch (ApostropheException $e)
    {
        var_dump($e);
        $val = 'UNKNOWN';
    }
    catch (ShortException $e)
    {
        var_dump($e);
    }

    echo "THE CURRENT VAL IS $val" . PHP_EOL;
}

Open in new window

HTH, ~Ray
0
 

Author Closing Comment

by:rgb192
ID: 39673544
thank you for the catch tutorial
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question