Deniss Muntjans Deniss Muntjans - 2 months ago 6
PHP Question

PHP - Don't load the page if exception is caught

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



When I call the
MyFunction
method like this:

$quotation = new Quotations\MyClass();
echo $quotationResult = $quotation -> MyFunction('A', 'B', 2, 'a');


to test if it will throw an exception but for some reason page doesn't load saying - "localhost is currently unable to handle this request". But when I call it like this:

$quotation = new Quotations\MyClass();
echo $quotationResult = $quotation -> MyFunction('A', 'B', 2, 3);


it works fine (I can see blank page).

Why it doesn't allow me to print an exception in the browser?

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";
}
}
}
?>

Answer

Use backslashes before the execption names to look for them in the global namespace. Otherwise, it looks for them in the Quotations namespace.

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";
    } 
}