5

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.

4

2 回答 2

4

如果你想要一个错误,你需要触发一个错误:

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

或者如果你喜欢有一些界面:

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();
于 2012-10-25T05:15:02.887 回答
1

这是由于 PHP 的动态类型特性而设计的,当然也没有明确的类型声明要求。变量类型是根据上下文确定的。

根据您的示例,当您这样做时:

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

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

调用is_int($c)当然总是会评估为布尔值 true,因为 PHP 已决定将语句的结果转换为整数。

如果你正在寻找解释器的错误,你不会得到它,因为就像我提到的那样,这是语言中内置的东西。您可能必须编写很多丑陋的条件代码来测试您的数据类型。

或者,如果您想这样做以测试传递给您的函数的参数 - 这是我能想到的唯一场景,您可能想要这样做 - 您可以相信调用您的函数的客户端知道他们在做什么。否则,返回值可以简单地记录为未定义。

我知道来自其他平台和语言,这可能很难接受,但信不信由你,很多用 PHP 编写的优秀库都遵循相同的方法。

于 2012-10-25T05:24:23.943 回答