// 好久没写php,最近语言切换有点多,可能有语法错误。
class Dog
{
private $name;
private $age;
private $sex;
private $master;
// 构造方法,传入狗狗基本信息
public function __construct($name, $age, $sex)
{
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
// 告诉狗狗主人是谁
public function setMaster($master)
{
$master->addDog($this);
$this->master = $master;
}
// 获取狗狗的主人
public function getMaster()
{
return $this->master;
}
}
class Master
{
private $name;
private $age;
private $dogs = [];
// 构造一个主人,传入主人信息
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
// 添加一个属于自己的狗狗
public function addDog($dog)
{
$dog->master = $this;
$this->dogs[] = $dog;
}
// 获取所有自己的狗狗
public function getDogs()
{
return $this->dogs;
}
}
$liming = new Master('liming', 22);
$xiaohei = new Dog('xiaohei', 2, 1);
$xiaobai = new Dog('xiaobai', 2, 0);
// 告诉小黑谁是主人
$xiaohei->master = $liming;
// 告诉小白谁是主任
$xiaobai->master = $liming;
// 获取小黑主人对象
$xiaohei->getMaster();
// 获取李明的所有狗狗对象列表
$liming->getDogs();