$foo = "0"; // $foo is a string (ASCII 48)
$foo++; // $foo is the string "1" (ASCII 49)
$foo += 1; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a double (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is a double (15)
$foo = 5 + "10 Small Pigs"; // $foo is an integer (15)
要改动变量的类型,也可用settype() 函数。
1、强迫类型转换
PHP中的强迫类型转换和C中一样: 在需求停止类型强迫转换的变量前的括号中写出想要的类型名。
$foo = 10; // $foo is an integer
$bar = (double) $foo; // $bar is a double
答应的强迫转换是:
(int), (integer) - cast to integer
(real), (double), (float) - cast to double
(string) - cast to string
(array) - cast to array
(object) - cast to object
$foo = 1 + "10.5"; // $foo is a double (11.5)
$foo = 1 + "-1.3e3"; // $foo is a double (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is a double (1)
$foo = 1 + "bob3"; // $foo is an integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is an integer (11)
$foo = 1 + "10 Little Piggies"; // $foo is a double (11); the string contains 'e'
凡是,你但愿依据前提履行多于一条语句。固然,不需求给每条语句都加上 IF 判别。取而代之,可以把多条语句构成一个语句组。
If语句可以嵌套于其他 IF语句中,使你可以天真地有前提的履行法式的各个局部。
2、 ELSE语句
凡是你但愿知足特定前提时履行一条语句,不知足前提是履行另外一条语句。ELSE就是用来做这个的。ELSE 扩大IF语句,在IF语句表达式为FALSE时履行另外一条语句。例如, 上面法式履行假如 $a 大于 $b则显示 'a is bigger than b',不然显示 'a is NOT bigger than b':
if ($a>$b) {
print "a is bigger than b";
}
else {
print "a is NOT bigger than b";
}
3、 ELSEIF语句
ELSEIF,就象名字所示,是IF和ELSE的组合,相似于 ELSE,它扩大 IF 语句在IF表达式为 FALSE时履行其他的语句。但与ELSE分歧,它只在ELSEIF表达式也为TRUE时履行其他语句。
function foo( &$bar ) {
$bar .= ' and something extra.';
}
$str = 'This is a string, ';
foo( $str );
echo $str; // outputs 'This is a string, and something extra.'
function foo( $bar ) {
$bar .= ' and something extra.';
}
$str = 'This is a string, ';
foo( $str );
echo $str; // outputs 'This is a string, '
foo( &$str );
echo $str; // outputs 'This is a string, and something extra.'
4、 默许值
函数可以界说 C++ 作风的默许值,以下:
function makecoffee( $type = "cappucino" ) {
echo "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee( "espresso" );
上边这段代码的输入是:
Making a cup of cappucino.
Making a cup of espresso.
注重,当利用默许参数时,一切有默许值的参数应在无默许值的参数的后边界说;不然,将不会按所想的那样任务。
5、CLASS(类)
类是一系列变量和函数的纠合。类用以下语法界说:
<?php
class Cart {
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
function remove_item($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} else {
return false;
}
}
}
?>
$ncart = new Named_Cart; // Create a named cart
$ncart->set_owner("kris"); // Name that cart
print $ncart->owner; // print the cart owners name
$ncart->add_item("10", 1); // (inherited functionality from cart)