【问题标题】:How to treat string as a string and not as an int in PHP如何将字符串视为字符串而不是 PHP 中的 int
【发布时间】:2012-10-15 05:52:23
【问题描述】:

我在阅读 PHP 手册时遇到了type juggling

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

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

当我使用此代码时,它返回 15,加起来是 10 + 5,当我使用 is_int() 时,它返回 true,即。 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 Little Piggies OR bob3 视为 string 而不是 int,我该怎么办。使用settype() 也不起作用。我想要一个无法将 5 添加到字符串的错误。

【问题讨论】:

  • -1 这个问题,认真的吗? com'on coward 过来回答我,为什么无缘无故地连续否决我的问题和答案?

标签: php type-conversion


【解决方案1】:

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

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

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

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

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

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

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

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

【讨论】:

  • 感谢您的详细解释
【解决方案2】:

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

$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();

【讨论】:

  • @Mr.Alien:取决于你的需要,是的。 PHP 没有“字符串”变量类型。这就是类型杂耍的意义所在。
  • 或者更好的措辞:PHP 没有用于添加的类型安全运算符。
  • 谢谢,我原以为 PHP 会抛出错误而不是自定义 1,但 PHP 让我失望了 :)
  • @Mr.Alien PHP 是动态且松散的类型,因此这是语言的本质 --- 根据个人喜好,它被视为一种特性或损害。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多