標籤:print 冒號 UI tle php apple 代碼 array obj
1、=>的用法
在php中數組預設鍵名是整數,也可以自己定義任一字元鍵名(最好是有實際意義),如:
$css=array(‘style‘=>‘0‘,‘color’=>‘green‘);
則$css[‘style‘]==‘0‘,$css[‘color‘]==‘green‘。
2、->的用法
->用來引用對象的成員(屬性與方法);
1 <?php 2 $arr=[‘a‘=>123,‘b‘=>456];//數組初始化 3 echo $arr[‘a‘];//數組引用 4 print_r($arr);//查看數組 5 class A{ 6 public $a=123; 7 public $b=456; 8 } 9 $obj=new A();10 echo $obj->a;//對象引用11 print_r($obj);//查看對象12 ?>
輸出結果:
123Array( [a] => 123 [b] => 456)123A Object( [a] => 123 [b] => 456)
3、::的用法
雙冒號操作符即範圍限定操作符Scope Resolution Operator可以訪問靜態、const和類中重寫的屬性與方法。
(1)Program List:用變數在類定義外部存取
1 <?php 2 class Fruit { 3 const CONST_VALUE = ‘Fruit Color‘; 4 } 5 6 $classname = ‘Fruit‘; 7 echo $classname::CONST_VALUE; // As of PHP 5.3.0 8 9 echo Fruit::CONST_VALUE;10 ?>
(2)Program List:在類定義外部使用::
1 2 <?php 3 class Fruit { 4 const CONST_VALUE = ‘Fruit Color‘; 5 } 6 7 class Apple extends Fruit 8 { 9 public static $color = ‘Red‘;10 11 public static function doubleColon() {12 echo parent::CONST_VALUE . "\n";13 echo self::$color . "\n";14 }15 }16 17 Apple::doubleColon();18 ?>
(3)Program List:調用parent方法
1 <?php 2 class Fruit 3 { 4 protected function showColor() { 5 echo "Fruit::showColor()\n"; 6 } 7 } 8 9 class Apple extends Fruit10 {11 // Override parent‘s definition12 public function showColor()13 {14 // But still call the parent function15 parent::showColor();16 echo "Apple::showColor()\n";17 }18 }19 20 $apple = new Apple();21 $apple->showColor();22 ?>
(4)Program List:使用範圍限定符
1 2 <?php 3 class Apple 4 { 5 public function showColor() 6 { 7 return $this->color; 8 } 9 }10 11 class Banana12 {13 public $color;14 15 public function __construct()16 {17 $this->color = "Banana is yellow";18 }19 20 public function GetColor()21 {22 return Apple::showColor();23 }24 }25 26 $banana = new Banana;27 echo $banana->GetColor();28 ?>
(5)Program List:調用基類的方法
1 2 <?php 3 4 class Fruit 5 { 6 static function color() 7 { 8 return "color"; 9 }10 11 static function showColor()12 {13 echo "show " . self::color();14 }15 }16 17 class Apple extends Fruit18 {19 static function color()20 {21 return "red";22 }23 }24 25 Apple::showColor();26 // output is "show color"!27 28 ?>
PHP關於=>和->以及::的用法