PHP difference between int and integer

前端 未结 4 724
情话喂你
情话喂你 2021-01-07 18:59

Is there any difference between int and integer in PHP?

Which is the newer or more recommended use?

$a = (int)\"3 euros\";
         


        
相关标签:
4条回答
  • 2021-01-07 19:19

    This is not quite true, there is actually a difference between int and integer. Here a simple example:

    //print_r('PHP version: '.phpversion().'<br />');
    //PHP version: 5.5.23
    
    $i = '1';
    
    function testme(int $j){
      print_r ($j);
    }
    testme(intval($i));
    

    This little portion of code will print an "E_RECOVERABLE_ERROR" since testme function is expecting 'int' and get 'integer' instead.

    0 讨论(0)
  • 2021-01-07 19:20

    Quoting the manual:

    Converting to integer

    To explicitly convert a value to integer, use either the (int) or (integer) casts. ...

    0 讨论(0)
  • 2021-01-07 19:20

    The difference arises when we use type hinting from php 7.0+

    this is valid

    function getId(): int 
    {
     return $id;
    }
    

    this is not

    function getId(): integer
    {
     return $id;
    }
    

    the second one will expect you to return an object of a 'class integer', which will cause a strange sentence:

    Uncaught TypeError: Return value of getId() must be an instance of integer, integer returned in ...
    
    0 讨论(0)
  • 2021-01-07 19:33

    No.

    They are the same, they both cast the value to an integer, one is just terser by four characters.

    Source.

    0 讨论(0)
提交回复
热议问题