如何将字符串视为字符串而不是PHP中的int

Mr.*_*ien 5 php type-conversion

我正在阅读PHP手册,我遇到了类型杂耍

我很困惑,因为我从未遇到过这样的事情.

$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
Run Code Online (Sandbox Code Playgroud)

当我使用这个代码时,它返回我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 */
Run Code Online (Sandbox Code Playgroud)

现在,如果我想将10只小猪或bob3视为一种string而不是一只,我该怎么办int?使用settype()也不起作用.我想要一个我无法在字符串中添加5的错误.

hak*_*kre 4

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

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

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

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();
Run Code Online (Sandbox Code Playgroud)