第三节:类型-数组:数组的高级应用

如果你不给数组键名加',默认情况下PHP也不会报错,而会自动进行取代,给他加上'。但是这种情况是要极力杜绝的,很容易产生混淆。

<?php
$arr=array('fruit'=>'apple','veggie'=>'carrot');
print $arr['fruit'];       //apple
print $arr['veggie'];  //carrot
print $arr[fruit];       //applle
define('fruit','veggie');
print $arr['fruit']     //apple
print $arr[fruit]     //carrot
?>

 

转换为数组

对于任意类型:integer,float,string,boolean and resource,如果将一个值转换为数组,将得到一个仅有一个元素的数组(其小标为0),该元素即为此标量的值。(arrary)$scalarValue与array($scalarValue)完全一样。

NULL 转换到 数组(array) 会得到一个空的数组。 

Object转换为数组会有两种形态:

如果一个对象被转换为一个数组,其结果是一个数组,其元素是对象的属性。键的成员变量的名称,有几个显着的例外:整数性能是不可访问的,私有变量的类名前缀的变量名,受保护的变量有“*”符号的变量名。这些前缀的值必须在任何一方的空字节。这可能会导致一些意想不到的行为:

 1 <?php
 2 
 3 class A {
 4     private $A; // This will become '\0A\0A'
 5 }
 6 
 7 class B extends A {
 8     private $A; // This will become '\0B\0A'
 9     public $AA; // This will become 'AA'
10 }
11 
12 var_dump((array) new B());
13 ?> 

输出:array(3) { ["BA"]=> NULL ["AA"]=> NULL ["AAAAA"]=> NULL }

 1 <?php
 2 
 3 class A {
 4     private $AAAA; // This will become '\0A\0A'
 5 }
 6 
 7 class B extends A {
 8     private $A; // This will become '\0B\0A'
 9     public $AA; // This will become 'AA'
10 }
11 $a=&new B();
12 var_dump(array($a));
13 ?> 

输出:array(1) { [0]=> object(B)#1 (3) { ["A:private"]=> NULL ["AA"]=> NULL ["AAAA:private"]=> NULL } }

 

posted @ 2013-01-15 15:38  saws  阅读(347)  评论(0编辑  收藏  举报