Zairov Muric Zairov Muric - 2 months ago 6
PHP Question

How to get a specific type in a function?

I want to use int only for $amount but I receive double sometimes so I am checking if its int. Is there a better way to do it? My problem is another class send data to it, and I want to prevent that they should not send any type.. is it possible?

my code:

function finTrian($amount, $source, $trian, $realTrian, $pos = -1)
{
if(!is_int($amount))
return;

if($amount < $requiredAmount)
return "E-1019";

$totalTrian = ($trian * $realTrian) / self::T_FACTOR;


...

}


?>


I am really having problem with this, sometimes application does not work correctly and I need to find the problem. Can someone please help me with this?

Thank you!!!

Answer

Yes, it is possible to do it..

Just change your code like below:

from:

function finTrian($amount, $source, $trian, $realTrian, $pos = -1)
{
  if(!is_int($amount))
    return;

  if($amount < $requiredAmount)
    return "E-1019";

to:

function finTrian(int $amount, $source, $trian, $realTrian, $pos = -1)
{
  if($amount < $requiredAmount)
    return "E-1019";

the $amount parameter will be converted to int if possible. @Eiko

Types has been added in php 7:

bool      PHP 7.0.0
float     PHP 7.0.0
int       PHP 7.0.0
string    PHP 7.0.0