BOOK Details program using class in PHP:
class Book {
public $title;
private $author;
private $pages;
public function __construct($title, $author, $pages) {
$this->title = $title;
$this->author = $author;
$this->pages = $pages;
}
public function getAuthor() {
return $this->author;
}
public function setAuthor($newAuthor) {
$this->author = $newAuthor;
}
public function getPages() {
return $this->pages;
}
public function getInfo() {
return "Title: " . $this->title . ", Author: " . $this->getAuthor() . ", Pages: " . $this->getPages();
}
}
// Create two book objects
$book1 = new Book("The Lord of the Rings", "J.R.R. Tolkien", 1137);
$book2 = new Book("Pride and Prejudice", "Jane Austen", 226);
// Access and modify properties (note private author requires getter/setter)
echo $book1->getInfo() . PHP_EOL; // Outputs: Title: The Lord of the Rings, Author: J.R.R. Tolkien, Pages: 1137
$book1->setAuthor("Frodo Baggins"); // Change author playfully
echo $book1->getInfo() . PHP_EOL; // Outputs: Title: The Lord of the Rings, Author: Frodo Baggins, Pages: 1137
// Demonstrate private property protection
echo "Trying to access private author directly: " . $book1->author . PHP_EOL; // Throws error: Cannot access private property Book::$author
Comments
Post a Comment