<?php
//换行输出
function println($var){
echo $var;
echo "<br />";
}
class Father{
private $name;
protected $money;
public $friends;
//构造函数初始化对象
function __construct(){
println("father construct executed...");
$this->name="father";
$this->money=10000.0;//父亲的初始财富值,也许是他爸爸留给他的
$this->friends=array("jack","lily");
}
function work(){
println("father working..");
$this->money+=10;//父亲通过工作挣钱
}
function printInfo(){
println("name:".$this->name);
println("money:".$this->money);
echo "friends:";
foreach($this->friends as $friend){
echo $friend." ";
}
echo "<br />";
}
function __destruct(){
println("father gone");
}
}
class Sun extends Father{
private $name;
private $other;
function __construct(){
println("sun construct executed...");
parent::__construct();//如果没有这行显示的调用父类的构造函数,那么父类的构造函数将不会执行
$this->name="sun";//儿子自己的名字
$this->other="somthing else";
}
function work(){
println("sun working..");
$this->money+=20;//儿子继承了父亲的财产,通过自己挣钱使财富值增加了(儿子挣钱的能力比父亲强)
}
//儿子有自己的朋友
function makeFriends(){
$this->friends=array("mike","tom","bake");
}
function printInfo(){
println("name:".$this->name);
println("money:".$this->money);
println("other:".$this->other);
echo "friends:";
foreach($this->friends as $friend){
echo $friend." ";
}
echo "<br />";
}
function __destruct(){
parent::__destruct();
println("sun gone");
}
}
//定义父亲对象
$father=new Father();
$father->work();
$father->printInfo();
println("========================");
//定义儿子对象,很多属性都继承自父亲
$sun=new Sun();
$sun->printInfo();
println("========================");
$sun->work();
$sun->makeFriends();
$sun->printInfo();
println("========================");
//接下来是系统自动销毁对象
?>
以上程序的输出结果为
father construct executed...
father working..
name:father
money:10010
friends:jack lily
========================
sun construct executed...
father construct executed...
name:sun
money:10000
other:somthing else
friends:jack lily
========================
sun working..
name:sun
money:10020
other:somthing else
friends:mike tom bake
========================
father gone
sun gone
father gone