Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat string as a string and not as an int in PHP

I was reading PHP manual and I came across type juggling

I was confused, because I've never came across such thing.

$foo = 5 + "10 Little Piggies"; // $foo is integer (15)

When I used this code it returns me 15, it adds up 10 + 5 and when I use is_int() it returns me true ie. 1 where I was expecting an error, it later referenced me to String conversion to numbers where I read If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero)

$foo = 1 + "bob3";             /* $foo is int though this doesn't add up 3+1 
                                  but as stated this adds 1+0 */

now what should I do if I want to treat 10 Little Piggies OR bob3 as a string and not as an int. Using settype() doesn't work either. I want an error that I cannot add 5 to a string.

like image 844
Mr. Alien Avatar asked Oct 25 '12 05:10

Mr. Alien


2 Answers

If you want an error, you need to trigger an error:

$string = "bob3";
if (is_string($string)) 
{
    trigger_error('Does not work on a string.');
}
$foo = 1 + $string;

Or if you like to have some interface:

class IntegerAddition
{
    private $a, $b;
    public function __construct($a, $b) {
        if (!is_int($a)) throw new InvalidArgumentException('$a needs to be integer');
        if (!is_int($b)) throw new InvalidArgumentException('$b needs to be integer');
        $this->a = $a; $this->b = $b;
    }
    public function calculate() {
        return $this->a + $this->b;
    }
}

$add = new IntegerAddition(1, 'bob3');
echo $add->calculate();
like image 56
hakre Avatar answered Sep 22 '22 19:09

hakre


This is by design as a result of PHP's dynamically typed nature and of course lack of an explicit type declaration requirement. Variable types are determined based on context.

Based on your example, when you do:

$a = 10;
$b = "10 Pigs";

$c = $a + $b // $c == (int) 20;

Calling is_int($c) will of course always evaluate to a boolean true because PHP has decided to convert the result of the statement to an integer.

If you're looking for an error by the interpreter, you won't get it since this is, like I mentioned, something built into the language. You might have to write a lot of ugly conditional code to test your data types.

Or, if you want to do that for testing arguments passed to your functions - that's the only scenario which I can think of where you might want to do this - you can trust the client invoking your function to know what they are doing. Otherwise, the return value can simply be documented to be undefined.

I know coming from other platforms and languages, that might be hard to accept, but believe it or not a lot of great libraries written in PHP follow that same approach.

like image 34
9ee1 Avatar answered Sep 24 '22 19:09

9ee1