2 回答
TA贡献1831条经验 获得超10个赞
class Dog{
public name;
public age;
public sex;
public onwer;
}
class Master{
public name;
public age;
public petDog;
}
//狗的信息
public function getDogOnwer(){
$newDog = new Dog();
echo $newDog->name;
echo $newDog->age;
echo $newDog->sex;
echo $newDog->onwer;
}
//master信息
public function getMasterInfo(){
$newMater = new Master();
echo $newMater->name;
echo $newMater->age;
echo $newMater->petDog;
}
TA贡献1864条经验 获得超2个赞
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | // 好久没写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(); |
- 2 回答
- 0 关注
- 467 浏览
添加回答
举报