双冒号::被认为是作用域限定操作符,用来指定类中不同的作用域级别。::左边表示的是作用域,右边表示的是访问的成员。
系统定义了两个作用域,self和parent。self表示当前类的作用域,在类之外的代码是不能使用这个操作符的。
Program List:使用self作用域访问父类中的函数
06 | print '我在类 NowaClass 中声明了。' ; |
10 | class ExtendNowaClass extends NowaClass |
12 | function extendNowaMethod() |
14 | print 'extendNowaMethod 这个方法在 ExtendNowaClass 这个类中声明了。' ; |
19 | ExtendNowaClass::extendNowaMethod(); |
程序运行结果:
1 | extendNowaMethod 这个方法在 ExtendNowaClass 这个类中声明了。 |
parent这个作用域很简单,就是派生类用来调用基类的成员时候使用。
Program List:使用parent作用域
10 | class ExtendNowaClass extends NowaClass |
12 | function extendNowaMethod() |
19 | $obj = new ExtendNowaClass(); |
20 | $obj -> extendNowaMethod(); |
程序运行结果:
Program List:用基类的方法访问派生类的静态成员
如何继承一个存储位置上的静态属性。
06 | echo $this ->connect(); |
09 | class Banana extends Fruit |
11 | private static $bananaColor ; |
12 | public function connect() |
14 | return self:: $bananaColor = 'yellow' ; |
17 | class Orange extends Fruit { |
18 | private static $orange_color ; |
19 | public function connect() |
21 | return self:: $orange_color = 'orange' ; |
24 | $banana = new Banana(); |
25 | $orange = new Orange(); |
程序运行结果:
Program List:静态函数初始化
在一个类中初始化静态变量比较复杂,你可以通过创建一个静态函数创建一个静态的构造器,然后在类声明后马上调用它来实现初始化。
04 | private static $color = "White" ; |
05 | private static $weigth ; |
06 | public static function init() |
08 | echo self:: $weigth = self:: $color . " Kilogram!" ; |
程序运行结果:
Program List:一个简单的单例模式例子
这个应该可以帮到某些人吧。
04 | private static $instance = null; |
05 | private function __construct() |
07 | $this -> color = 'Green' ; |
09 | public static function getInstance() |
11 | if (self:: $instance == null) |
13 | print "Fruit object created!<br />" ; |
14 | self:: $instance = new self; |
16 | return self:: $instance ; |
18 | public function showColor() |
20 | print "My color is {$this-> color}!<br>" ; |
22 | public function setColor( $color ) |
24 | $this -> color = $color ; |
27 | $apple = Fruit::getInstance(); |
29 | $apple -> setColor( "Red" ); |
31 | $banana = Fruit::getInstance(); |
32 | $banana -> showColor(); |
33 | $banana -> setColor( "Yellow" ); |
程序运行结果: