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