0

In JavaScript this is how I create throw errors if the parameter of a function is a invalid type.

function myFunction(num)
    if (typeof(num) !== 'number') {
        throw TypeError('num cannot be' + num);
    }
}

How do I do this on PHP? I know there is a throw command but how do you set the error type. In the JavaScript example above I set it to be a TypeError, how do you set the error type for a PHP throw error and what are the error types in PHP?

function myFunction($num)
    if (gettype($num) !== 'boolean') {
        throw new Exception('$num cannot be ' , $num);;
    }
}
bhutto54
  • 7
  • 3
  • php have is_type commands. If you want control boolean use `if(!is_bool($num))` details in https://www.php.net/manual/en/function.is-bool.php – xNoJustice Jul 28 '20 at 18:17
  • `if (!is_bool($num)) throw new Exception('$num can not be ' . $num);` – Markus Zeller Jul 28 '20 at 18:17
  • 2
    PHP has exception classes: https://www.php.net/manual/en/spl.exceptions.php – Barmar Jul 28 '20 at 18:18
  • 2
    If you're using PHP 7, simply specify the argument type: `function myFunction(bool num)` and [enable strict types](https://stackoverflow.com/questions/48723637/what-do-strict-types-do-in-php). No need to do anything else but use the language features that are already in place. – Jeto Jul 28 '20 at 18:20

2 Answers2

0

PHP has exception classes much like JavaScript does.

function myFunction($num)
    if (!is_bool($num)) {
        throw new InvalidArgumentException('$num cannot be ' . $num);;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can try create you custom exception exemple

  final class CustomException extends \DomainException
{
    
    public function __construct()
    {
        $this->message = 'My Custom Message';
        $this->code = 400;
    }
}

and use:

throw new CustomException();

or use generic exception

throw new \Exception('message', 400);

Exception have methods getMessage() and getCode()