1 <?php
2 // You can also use arrays
3 $baz = array("value" => "foo");
4 echo "this is {$baz['value']} !"; // this is foo !
5
6 $foo = "foobar";
7 $bar = "barbaz";
8 // If you are not using any other characters, you can just echo variables
9 echo $foo; // foobar
10 echo $foo,$bar; // foobarbarbaz
11
12 // Because echo does not behave like a function, the following code is invalid.
13 ($some_var) ? echo 'true' : echo 'false';
14 // However, the following examples will work:
15 ($some_var) ? print 'true' : print 'false'; // print is also a construct, but
16 // it behaves like a function, so
17 // it may be used in this context.
18 echo $some_var ? 'true': 'false'; // changing the statement around
19
20 //相对 echo 中拼接字符串而言,传递多个参数比较好,考虑到了 PHP 中连接运算符(“.”)的优先级。 传入多个参数,不需要圆括号保证优先级:
21 echo "Sum: ", 1 + 2;
22 echo "Hello ", isset($name) ? $name : "John Doe", "!";
23 //如果是拼接的,相对于加号和三目元算符,连接运算符(“.”)具有更高优先级。为了正确性,必须使用圆括号:
24 echo 'Sum: ' . (1 + 2);
25 echo 'Hello ' . (isset($name) ? $name : 'John Doe') . '!';
1 <?php
2 ($some_var) ? print 'true' : print 'false'; //具体参见echo用例
3
4 //另外因为print是语言构造器,而不是函数,其园括号不是必须的。在一些使用场景下可能引发问题。例如:
5 //这部分代码来源:http://php.net/manual/zh/function.print.php#85310
6 <?php
7 if (print("foo") && print("bar")) {
8 // 打印出来的是“bar1” 原因不明,没弄懂
9 }
10
11 //对于期待的输出,应该这么写:
12 if ((print "foo") && (print "bar")) {
13 // da打印出来的是“foobar”
14 }
1 <?php
2 $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z'));
3 print_r ($a);
4 /******
5 打印输出如下
6 Array
7 (
8 [m] => monkey
9 [foo] => bar
10 [x] => Array
11 (
12 [0] => x
13 [1] => y
14 [2] => z
15 )
16
17 )
18 ******/
19 $results = print_r ($b, true); //$results 包含了 print_r 的输出结果
20 var_dump($results);
21 /*****
22 Array
23 (
24 [m] => monkey
25 [foo] => bar
26 [x] => Array
27 (
28 [0] => x
29 [1] => y
30 [2] => z
31 )
32
33 )
34 ******/
1 <?php
2 $a = array (1, 2, array ("a", "b", "c"));
3 var_export ($a);
4
5 /* 输出:
6 array (
7 0 => 1,
8 1 => 2,
9 2 =>
10 array (
11 0 => 'a',
12 1 => 'b',
13 2 => 'c',
14 ),
15 )
16 */
17 $aa = var_export($a,true);
18 eval('$aaa='.$aa.';'); //这时,$aaa就是有和$a相同的数组了。
19
20 $b = 3.1;
21 $v = var_export($b, TRUE);
22 echo $v;
23
24 /* 输出:
25 3.1
26 */
27
28 class A{
29 public $a=1;
30 public $b=2;
31 }
32
33 $tmp = new A;
34 var_export($tmp);
35
36 class A{
37 public $a=1;
38 public $b=2;
39 }
40
41 $tmp = new A;
42 var_export($tmp);
43 /* 输出
44 A::__set_state(array(
45 'a' => 1,
46 'b' => 2,
47 ))
48 */