parent
self
static
parent
self
static
2014-09-29
parent用于调用父类的静态成员方法
self与static都可以用于访问类自身定义的静态成员方法,
<?php
date_default_timezone_set("PRC");
/**
1 静态属性用于保存类的共有数据
2 静态方法里面只能访问静态属性
3 静态成员不需要实例化对象就可以访问
4 类的内部可以通过self或者static关键字访问自身静态成员
5 可以通过parent关键字访问父类的静态成员
6可以通过类的名称在定义外部访问静态成员
*/
class Human{
public $name;
protected $height;
public $weight;
private $isHungry=true;
public static $sValue = "Static value in Human class.";
public function eat($food){
echo $this->name."'s eating".$food."\n";
}
}
class Nbaplayer extends Human {
public $team = "bull";
public $playerNumber = "23";
private $age = "40";
//静态属性定义时候在访问关键字后面添加static 关键字即可
public static $president = "David Stern";
//静态方法定义
public static function changepresident($newprsdt){
//在类中定义使用静态成员时候,用self关键字后跟着属性名
//注意,在访问静态成员的时候,::后面需要跟符号$
self::$president = $newprsdt; //用static也可以
//使用parent关键字就能访问父类的静态成员
echo parent::$sValue."\n";
}
function __construct($name,$height,$weigh,$team,$playerNumber){
echo "In Nbaplayer constructor\n";
$this->name = $name;
$this->height = $height;
$this->team = $team;
$this->playerNumber = $playerNumber;
}
function __destruct(){
echo "Destroying".$this->name."\n";
}
public function run(){ //定义方法
echo "running\n";
}
public function jump(){
echo "jumpping\n";
}
public function dribble(){
echo "dribbing\n";
}
public function dunk(){
echo "dunking\n";
}
public function pass(){
echo "passing\n";
}
public function getAge(){
echo $this->name.".'s age is".($this->age - 2 )."\n";
}
}
//类的实例化为对象时使用关键字new,new之后紧跟类名和一对括号
//在类定义外部访问静态属性,我们可以用类名加::属性名来调用静态成员
echo Nbaplayer::$president . "before change\n";
Nbaplayer::changepresident("Adam Silver");
echo Nbaplayer::$president ."\n";
echo Human::$sValue."\n";
//所有的对象共用一个属性
?>
举报