文章目录
基本输出语句echo和print
在PHP中,有两种基本的输出方法:echo和print。
echo和print差异
- echo 能够输出一个以上字符串
- print 只能输出简单类型变量的值,如int,string并始终返回1
- print_r 可以输出复杂类型变量的值,如数组,对象
- echo比print稍快,因为它没有返回值;print和print_r是PHP函数,函数有返回值。
- print返回值为1(int类型),print_r返回值为true(bool类型)。
echo
echo是一个语言结构,有无括号均可使用:echo或echo(),这一点与Python2和3很相似。
显示变量和字符串
<?php
$x=10;
$y=20;
$z=$x+$y;
$text="PHP is the best language in the world!";
echo "z=$z<br/>";
echo $text;
echo "<br/>";
echo "I'm about to learn PHP!<br/>";
echo "This", " string", " was", " made", " with multiple parameters.";
?>
其中,<br/>
用于换行.
print 同样是一个语言结构,可以使用括号,也可以不使用括号: print 或 print()。
显示变量和字符串
<?php
$sen=array("I am ","about to ","learn PHP");
$text="PHP is the best language in the world!";
print "<h2>PHP is fun!</h2>";
print $text;
print "<br/>";
print "{$sen[0]}{$sen[1]}{$sen[2]}";
?>
print_r()
print_r 显示关于一个变量的易于理解的信息,如果给出的是 string、integer 或 float,将打印变量值本身。
如果给出的是 array,将会按照一定格式显示键和元素。object与数组类似。
print_r()会将把数组的指针移到最后边。使用 reset() 可让指针回到开始处。
<?php
$txt1="Hello World!";
$cars=array("Volvo","BMW","Toyota");
print_r($txt1);
print_r("<br/>Cars:<br/>");
print_r($cars);
?>
PHP 5 数据类型
数据类型概述
var_dump()函数
PHP var_dump() 函数返回变量的数据类型和值。
<?php
$cars=array("Volvo","BMW","Toyota");
$num=19.02;
var_dump($cars);
var_dump($num);
?>
运行结果显示,数组cars的数据类型均为string,长度分别为5、3、6,变量num的数据类型为浮点数。
PHP 对象
在PHP中,对象必须先声明后使用,对象数据类型也可以用于存储数据。
首先,你必须使用class关键字声明类对象。类是可以包含属性和方法的结构。然后在实例化的类中使用数据类型。
<?php
class Car
{
var $color;
function Car($color="green") {
$this->color = $color;//字this就是指向当前对象实例的指针,不指向任何其他对象或类。
}
function what_color() {
return $this->color;
}
}
function print_vars($obj) {
foreach (get_object_vars($obj) as $prop => $val) {
echo " $prop = $val
";
}
}
// instantiate one object
$herbie = new Car("white");
// show herbie properties
echo "herbie: Properties
";
print_vars($herbie);
?>