PHP入门 - 面向对象 发表于 2015-08-12 | 分类于 PHP | 类的声明123456class Hello { public function sayello() { echo 'Hello PHP'; }} 类的实例化1$h = new Hello(); 类方法的引用1$h->sayello(); 类的构造器和外部形参12345678910111213141516171819202122232425class Man { /** * Man constructor. * @param int $age 年龄 * @param string $name 名字 */ public function __construct($age, $name) { echo 'coustruct'; $this->_age = $age; $this->_name = $name; } public function getAge() { return $this->_age; } public function getName() { return $this->_name; } private $_age, $_name;} 类方法的声明和使用12345678class Man { public static function sayHello() { echo 'Hello Men'; }}Man::sayHello(); PHP静态属性的声明和使用:1234567891011121314151617181920class Man { public function __construct($age, $name) { echo 'coustruct'; $this->_age = $age; $this->_name = $name; Man::$NUM++; if (Man::$NUM>Man::MAX_NUM) { throw new Exception('不能创建更多的MAN'); } } private $_age, $_name; private static $NUM = 0; const MAX_NUM = 100;}for ($i=0; $i<200; $i++) { $m = new Man($i,'Geek');} 静态的属性和方法是为了描述类的信息,比如以上描述的就是初始人数是0,最大人数是100,成员属性和方法是为了描述类的实例。 类的继承1234567891011121314151617181920212223242526class People { public function __construct($age, $name, $sex) { $this->_age = $age; $this->_name = $name; $this->_sex = $sex; } public function sayHi() { echo $this->_name.' say hi'; } private $_age, $_name, $_sex;}class Women extends People { public function __construct($age, $name) { parent::__construct($age, $name, '女'); }}$w = new Women(10, 'Geek');$w->sayHi(); 重写类方法1234567891011121314151617181920212223242526272829class People { public function __construct($age, $name, $sex) { $this->_age = $age; $this->_name = $name; $this->_sex = $sex; } public function sayHi() { echo $this->_name.' say hi'; } private $_age, $_name, $_sex;}class Women extends People { public function __construct($age, $name) { parent::__construct($age, $name, '女'); } public function sayHi() { echo 'women '.$this->getName().' say hi'; }}$w = new Women(10, 'Geek');$w->sayHi();