Deniss Muntjans
Deniss Muntjans

Reputation: 379

Where to include PHP exception in the class?

I'm new to OO PHP...I'm trying to create a PHP class called MyClass and some methods that should:

  1. validate that parameters are numeric
  2. validate that parameters are defined
  3. if any of the above fail I need to send an exception with explanation

I've done 1. and 2. but don't know how to deal with exceptions, where you need to include them? Inside MyFunction method of inside isNumeric/isDefined methods. Could you please help to sort this issue.

My script:

<?php

namespace Quotations;

class MyClass {

var $is_number;
var $is_defined;
private $number;
private $defined;

private function isNumeric($w, $c){
    if(is_numeric($w) && is_numeric($c)){
        $number = true;
    }
    else{
        $number = false;
    }

    return $number;
}

private function isDefined($t, $f, $w, $c){
    if(isset($t, $f, $w, $c)){
        $defined = true;
    }
    else{
        $defined = false;
    }

    return $defined;
}

function MyFunction($to, $from, $weight, $cube) {
    try{
        if(!$this -> isNumeric($weight, $cube)){
            throw new InvalidArgumentException('Arguments are not numeric');
        }

        if(!$this -> isDefined($to, $from, $weight, $cube)){
            throw new BadMethodCallException('Arguments are missing');
        }
    }catch(InvalidArgumentException $e){
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }catch(BadMethodCallException $e){
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    } 
}

?>

Upvotes: 0

Views: 661

Answers (1)

Alexey Chuhrov
Alexey Chuhrov

Reputation: 1787

I would suggest something like this:

function MyFunction($to, $from, $weight, $cube) {
    if(!$this -> isDefined($to, $from, $weight, $cube)){
        throw new \BadMethodCallException('Arguments are missing');
    }
    if(!$this -> isNumeric($weight, $cube)){
        throw new \InvalidArgumentException('Arguments are not numeric');
    }
    //do stuff
}

And thats how you can handle it:

try{
    $MyClassObject->MyFunction($arg1, $arg2, $arg3, $arg4);
}catch(BadMethodCallException $e){
    //handle missing arguments ...
}catch(InvalidArgumentException $e){
    //handle invalid argumets ...
}

So, thats just an example of basic usage. Feel free to adjust it however you want.

Note, if you have missing non-optional arguments in function, PHP will produce E_WARNING

Upvotes: 1

Related Questions