用的是php开发。相关代码如下:
代码1:使用静态属性
class NBAplayer {
public static $president = "david stern";
}
$tao = new NBAplayer('tao');
$jun = new NBAplayer('jun');
echo NBAplayer::$president; // david stern
代码2:使用继承
class Human {
public $name;
public $president = 'david stern';
}
class NBAplayer extends Human {
function __construct($name){
$this ->name = $name;
}
}
$tao = new NBAplayer('tao');
$jun = new NBAplayer('jun');
echo $tao ->president;
echo $jun ->president;
这两种方法都能保存公有属性,既然可以继承父类的共同的数据,那为什么还要static静态属性呢?
我是刚学习面向对象,理解不是很清楚,请大神讲讲他们在公有数据这方面的区别。