Re: What do we need strict scalar type hints for?

From: Date: Tue, 03 Feb 2015 20:23:36 +0000
Subject: Re: What do we need strict scalar type hints for?
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-81737@lists.php.net to get a copy of this message
I would prefer: function addVat($amount) { validateAmount($amount); return round($amount*1.19, 2); } function validateAmount($amount) { if (!is_int($amount) && !is_float($amount)) { throw new InvalidArgumentException('Argument amount must be of the type int|float, '.gettype($amount).' given'); } } Regards Thomas Sven Drieling wrote on 03.02.2015 20:07: > Am Mon, 02 Feb 2015 23:38:21 +0100 > schrieb Christoph Becker <cmbecker69@gmx.de>: > > Hallo, > >> >> addVat(-1); >> >> Well, my point was that even a strict type system doesn't necessarilly >> catch all erroneous/undesired arguments. Even if addVat() properly >> handles negative numbers, and maybe even zeroes, there are functions >> that can't. > > What about scalar type declaration in userland? > > > namespace mytypes; > > > declare scalartype amount($amount) { > if (!is_int($amount) && !is_float($amount)) { > throw new InvalidArgumentException('Argument amount > must be of the type int|float, '.gettype($amount).' given'); > } > } > > > function addVat(mytypes\amount $amount) { > return round($amount*1.19, 2); > } > > addVat(42) // OK > addVat("42") // OK > addVat(-42) // OK > addVat(42.0) // OK > addVat(true) // Exception > > > var mytypes\amount $amount = 0; > > $amount = 42; // OK > $amount = "42"; // OK > $amount = true; // Exception > > > > tschuess > [|8:) >

« previous php.internals (#81737) next »