在一个类中使用另一个类的属性(对应于外键)



我创建了两个表,一个表对应于书(id book主键、标题和可用性(布尔)),另一个表对应于借阅者(id借款人主键、名称、是否借阅(布尔)和id book外键)。

我创建了两个类。book类:

<?php
class Book {
public $id_Book, $price, $title, $available;
function __construct($id_Book, $price, $title, $available){
$this->id_Book = $id_Book;
$this->price= $price;
$this->title= $title;
$this->available = $available;
}

function setPrice($price) {
$this->price = $price;
}
function getPrice() {
return $this->price;
}
function setAvailable($available) {
$this->available = $available;
}
function getAvailable() {
return $this->available;
}
function getIdBook() {
return $this->id_Book;
}
function getTitle() {
return $this->title;
}

}

和一个借用类:

class Borrower {
public $id_Borrower, $name, $password, $id_BookBorrowed;
function __construct($id_Borrower, $name, $password, $id_BookBorrowed, $hasBorrowed){
$this->id_Borrower = $id_Borrower;
$this->name= $name;
$this->password= $password;
$this->id_BookBorrowed = $id_BookBorrowed;
$this->hasBorrowed = $hasBorrowed;
}
// getters and setters
function getName() {
return $this->name;
}
function getIdBookBorrowed() {
return $this->id_BookBorrowed;
}
function getHasBorrowed() {
return $this->hasBorrowed;
}
function setHasBorrowed($borrowed) {
$this->hasBorrowed = $borrowed;
}
function setIdBookBorrowed($id_BookBorrowed) {
$this->id_BookBorrowed = $id_BookBorrowed;
}

//function to borrow a book 
function BorrowBook(int $idBookToBorrow)  {
// we look if hasBorrow is true or not, if true then we can't, if false we can

if(!$this->HasBorrowed){
// we set idBookBorrowed

$this->setIdBookBorrowed($idBookToBorrow);
// we also need to put the book non available
// we put HasBorrowed to true
$this->setHasBorrowed(true);




}
else{
// function to show error mess
}
}
//function to return book 
function ReturnBook(int $idBookToBorrow)  {
// we check if hasBorrow is true or not, if true then we can return it, if not show error

if($this->HasBorrowed){
// we set idBookBorrowed to available, and set hasBorrow to false
$this->setHasBorrowed(false);


}
else{
// show error message
}
}

}
如你所见,我必须创建两个方法:一个用来借书,另一个用来还书。

然而,我必须找到书的id(所以是书类的id)。我该怎么做?

另外,你认为代码怎么样?

提前谢谢你

  • Borrower class,您可以删除$id_BookBorrowed, $hasBorrowed

  • Borrower class中,可以通过add_book_idremove_book_id方法添加数组属性borrowed_book_ids = []

  • 你可能需要$borrowed_by数组在你的book类中,如果书的数量可以大于1,看到借阅者的id集。

  • 您可以在https://codereview.stackexchange.com/

    中获得检查代码的帮助。

最新更新