Static(静态)关键字

通过函数改变内部属性的值:

 1 php
 2 
 3 class Human{
 4     public $name;
 5     protected $height;  
 6     public $weight;
 7     private $isHungry = true; 
 8 
 9 }
10 
11 
12 class NbaPlayer extends Human{
13     
14     public $team="Bull";
15     public $playerNumber="23";
16 
17     public $president = "David Stern";
18 
19     public function changePresident($newPrsdt) {
20         $this->president = $newPrsdt;
21     }   
22 }
23 
24 $jordan = new NbaPlayer("Jordan","198cm","98kg","Bull","23");
25 $james = new NbaPlayer("James","203cm","120kg","Heat","6");
26 
27 $jordan->changePresident("Adan Silver");
28 echo "Jordan:".$jordan->president ."
"; 29 echo "James:".$james->president ."
";

这时,通过 $jordan->changePresident("Adan Silver"); 来改变jordan的president,

如何同时改变jordan和james的president的值呢,这就需要使用Static静态变量了

 1 php
 2 
 3 class Human{
 4     public $name;
 5     protected $height;  
 6     public $weight;
 7     private $isHungry = true; 
 8 
 9 }
10 
11 
12 class NbaPlayer extends Human{
13     
14     public $team="Bull";
15     public $playerNumber="23";
16     //静态属性定义在访问控制关键字后面添加static关键字即可
17     public static $president = "David Stern";
18     //静态方法实在function前面加上static
19     public static function changePresident($newPrsdt) {
20         //在类定义使用静态成员的时候,用self关键字后面跟着::操作符
21         //在访问静态成员属性的时候,::后面需要跟$符号
22         self::$president = $newPrsdt;
23     }   
24 }
25 //在类定义外部访问静态属性,我们可以用类名加::操作符来访问类的静态成员
26 echo NbaPlayer::$president." before changed"."
"; 27 NbaPlayer::changePresident("Adam Silver"); 28 echo NbaPlayer::$president." after changed" . "
";

输出结果:

1 David Stern before changed
2 Adam Silver after changed

 

然后我们再讨论子类静态函数调用父类的静态变量

 1 php
 2 
 3 class Human{
 4     public $name;
 5     protected $height;  
 6     public $weight;
 7     private $isHungry = true; 
 8     public static $sValue= "static value in Human class "."
"; 9 10 } 11 12 class NbaPlayer extends Human{ 13 14 public $team="Bull"; 15 public $playerNumber="23"; 16 private $age = "40"; 17 //静态属性定义在访问控制关键字后面添加static关键字即可 18 public static $president = "David Stern"; 19 //静态方法实在function前面加上static 20 public static function changePresident($newPrsdt) { 21 //在类定义使用静态成员的时候,用self或者static关键字后面跟着::操作符 22 //在访问静态成员属性的时候,::后面需要跟$符号 23 self::$president = $newPrsdt; 24 //使用parent关键字就能够访问父类的静态成员 25 echo parent::$sValue; 26 //静态函数不能访问动态的属性 27 //echo->age; 这里会出错 28 } 29 } 30 //在类定义外部访问静态属性,我们可以用类名加::操作符来访问类的静态成员 31 echo NbaPlayer::$president." before changed"."
"; 32 NbaPlayer::changePresident("Adam Silver"); 33 echo NbaPlayer::$president." after changed" . "
"; 34 //输出父类的静态变量 35 echo Human::$sValue;

输出为:

David Stern before changed
static value in Human class 
Adam Silver after changed
static value in Human class

总结起来就六点:

1、静态属性用于保存类的公有数据
2、静态方法里面只能访问静态属性
3、静态成员不需要实例化对象就可以访问
4、类的内部可以通过self或者static关键字访问自身静态成员
5、可以通过parent关键字访问父类的静态成员
6、可以通过类的名称在类的定义外部访问静态成员

 

转载于:https://www.cnblogs.com/jacson/p/4620409.html

你可能感兴趣的:(Static(静态)关键字)