2 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
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貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
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 | // 好久沒(méi)寫(xiě)php,最近語(yǔ)言切換有點(diǎn)多,可能有語(yǔ)法錯(cuò)誤。 class Dog { private $name; private $age; private $sex; private $master; // 構(gòu)造方法,傳入狗狗基本信息 public function __construct($name, $age, $sex) { $this->name = $name; $this->age = $age; $this->sex = $sex; } // 告訴狗狗主人是誰(shuí) public function setMaster($master) { $master->addDog($this); $this->master = $master; }
// 獲取狗狗的主人 public function getMaster() { return $this->master; } } class Master { private $name; private $age; private $dogs = [];
// 構(gòu)造一個(gè)主人,傳入主人信息 public function __construct($name, $age) { $this->name = $name; $this->age = $age; }
// 添加一個(gè)屬于自己的狗狗 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); // 告訴小黑誰(shuí)是主人 $xiaohei->master = $liming;
// 告訴小白誰(shuí)是主任 $xiaobai->master = $liming;
// 獲取小黑主人對(duì)象 $xiaohei->getMaster();
// 獲取李明的所有狗狗對(duì)象列表 $liming->getDogs(); |
- 2 回答
- 0 關(guān)注
- 488 瀏覽
添加回答
舉報(bào)