PHP 类的继承

一个父类,一个子类(People.php):


<?php
class People {
	private $name;
	private $age;
	function __construct() {
		// 构造方法
		$this->age = 20;
		$this->name = "noname";
	}
	function __destruct() { // 析构方法,因为PHP的特性,页面载入完就会销毁所有对象
		echo "销毁对象" . $this->name;
	}
	/**
	 * setter和getter
	 *
	 * @return the $name
	 */
	public function getName() {
		return $this->name;
	}
	
	/**
	 *
	 * @return the $age
	 */
	public function getAge() {
		return $this->age;
	}
	
	/**
	 *
	 * @param field_type $name        	
	 */
	public function setName($name) {
		$this->name = $name;
	}
	
	/**
	 *
	 * @param field_type $age        	
	 */
	public function setAge($age) {
		$this->age = $age;
	}
	public function say() {
		echo $this->name. $this->age;
	}

}
class Student extends People {
	//继承People
	public $id;
	public function study() {
		echo "我在学习";
	}
	
	public function say() {
		echo parent::getName().parent::getAge().$this->id;
		//访问父类方法读取
		
	}

}
?>

使用:


<?php
require_once 'People.php';
$stu=new Student();
$stu->setAge(23);
$stu->setName("张三");
$stu->id=232432;
$stu->say();
$stu->study();
?>

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记