1

今天我很想知道,如果字符串包含第一个字母有整数,你可以将该值添加到另一个整数变量中。

$a = 20;
$b = "5doller"; 
$a+=$b;
echo $a;

任何人都可以解释这是如何发生的,如果我有像“dollar5”这样的字符串,它不会添加。

4

2 回答 2

3

PHP 不是强类型的。
因为您的字符串的第一个字符是一个整数,并且您使用 + 运算符,它将 5dollar 解释为 int 并返回 25 个
示例:http ://en.wikipedia.org/wiki/Strong_typing#Example

于 2013-03-18T11:39:26.807 回答
0

PHP 有一个类型转换的理念,它会根据上下文在运行时自动转换数据的类型。这可能有它的优点和缺点,有人反对它,也有人认为它可以(就像生活中的几乎所有事情一样)。

有关其行为的更多信息,请查看 php 文档:http ://www.php.net/manual/en/language.types.type-juggling.php

如果您使用算术运算符“+”(检测第一个字符“5”),它将尝试将其string视为一种integer轻松的生活,但如果操作不当会导致奇怪的行为。

这并不意味着它没有类型, $b 实际上是 a string,只是它尝试在运行时转换它,但 $b 仍将保留为 a string

要检查这一点和/或防止奇怪的行为,您可以使用 php 本机函数来检查类型:

$a = 20;
$b = "5doller";
if(is_integer($b)){
    $a+=$b;
} elseif (is_string($b)) {
    $a.=$b;
}
echo $a;

Or you can use gettype() which will return the variable type, and do a switch case or whatever you like to it. But in my opinion it would be over-coding, just use your common sense and be careful and normally it will be ok.

于 2013-03-18T11:59:48.093 回答