2012-10-25 53 views
5
一个int

我阅读PHP手册和我碰到type juggling如何看待字符串作为一个字符串,而不是在PHP

我很困惑,因为我从来没有碰到过这样的事情来了。

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

当我用这个代码,它返回我15,它增加了10 + 5,当我使用is_int()它返回我真即。 1,我在等一个错误,它以后引用我String conversion to numbers在那里我阅读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 */ 

现在我应该怎么做,如果我想治疗10只小小猪或bob3为string,而不是作为一个int。使用settype()也不起作用。我想要一个错误,我不能将5添加到字符串中。

+0

-1问题严重吗? com'on懦夫来吧,并回答我,为什么连续无故地降低我的问题和答案? –

回答

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(); 
+2

Vooooo,所以我要抛出一个自定义错误? –

+1

@ Mr.Alien:根据你的需要,是的。 PHP没有“字符串”变量类型。这就是玩杂耍的意义所在。 – hakre

+0

或者更好的措词:PHP没有类型安全的操作符来添加。 – hakre

1

这是设计为PHP的动态的结果键入的性质,当然缺乏明确的类型声明要求。根据上下文确定变量类型。

根据您的例子,当你做:

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

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

调用is_int($c)当然会始终为一个true,因为PHP已经决定语句的结果转换为整数。

如果您正在寻找解释器发现的错误,您将无法得到它,因为正如我所提到的那样,该语言内置了一些内容。您可能需要编写大量难看的条件代码来测试您的数据类型。

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

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

+0

感谢您的详细解释 –

相关问题