PHP双冒号::的用法
2010-09-05
双冒号操作符即作用域限定操作符Scope Resolution Operator可以访问静态、const和类中重写的属性与方法。
在类定义外使用的话,使用类名调用。在PHP 5.3.0,可以使用变量代替类名。
Program List:用变量在类定义外部访问
04 |
const CONST_VALUE = 'Fruit Color'; |
08 |
echo $classname::CONST_VALUE; // As of PHP 5.3.0 |
10 |
echo Fruit::CONST_VALUE; |
Program List:在类定义外部使用::
04 |
const CONST_VALUE = 'Fruit Color'; |
07 |
class Apple extends Fruit |
09 |
public static $color = 'Red'; |
11 |
public static function doubleColon() { |
12 |
echo parent::CONST_VALUE . "\n"; |
13 |
echo self::$color . "\n"; |
程序运行结果:
Program List:调用parent方法
05 |
protected function showColor() { |
06 |
echo "Fruit::showColor()\n"; |
10 |
class Apple extends Fruit |
12 |
// Override parent's definition |
13 |
public function showColor() |
15 |
// But still call the parent function |
17 |
echo "Apple::showColor()\n"; |
程序运行结果:
Program List:使用作用域限定符
05 |
public function showColor() |
15 |
public function __construct() |
17 |
$this->color = "Banana is yellow"; |
20 |
public function GetColor() |
22 |
return Apple::showColor(); |
27 |
echo $banana->GetColor(); |
程序运行结果:
Program List:调用基类的方法
06 |
static function color() |
11 |
static function showColor() |
13 |
echo "show " . self::color(); |
17 |
class Apple extends Fruit |
19 |
static function color() |
26 |
// output is "show color"! |
程序运行结果: