2 回答

TA貢獻1836條經驗 獲得超5個贊
在你的構造函數中__construct
你應該做類似的事情:
$this -> rating = $rating;
不是:
$this -> rate = $rate;

TA貢獻1829條經驗 獲得超4個贊
你從哪里得到$rate變量?基本上沒啥地方用。如果$Rating進來,并且$this->Rating是全局變量,那么就沒有$Rate變量。
$this->title和 等之間也沒有空格。
代碼:
<?php
// Use this function to make sure your error handling is tightest:
error_reporting(E_ALL);
// Start a new class
class Book {
// We are setting the rating to be private:
private $rating;
// And we are setting the title to be public: You could also use 'var' here instead:
var $title;
// This is the function behind new Book () .. it is a construction function.
function __construct ($title, $rating) {
// You have $title coming and you are setting the classes global variable to it as well:
$this->title = $title;
// Same as above, but this is private, so outside of this class you cant access it:
$this->rating = $rating;
}
// This the function to get the rating:
function getRating () {
// This is the variable from the 5th line now. It is in fact private, but since the
// function is inside the class, then this function getRating is allowed to access the variable
// there for it will print it out without problems:
return $this->rating;
}
}
// Init the class and insert some basic information:
$book1 = new Book('Harry Potter', 'PG-13');
// Will print out 'PG-13'
echo $book1->getRating() . '<br>';
// Title will show up, as it is public:
echo $book1->title . '<br>';
// But accessing the rating directly, will not show anything:
echo $book1->rating . '<br>';
// Since the rating is private, then it will ultimate throw an error,
// so this will kill the script or show the error, depending on your hosting settings:
echo 'This probably wount show up';
// yup, it gives you:
// Fatal error: Uncaught Error: Cannot access private property Book::$rating in [.........]
?>
輸出:
希望這可以幫助您進一步學習更多 PHP。
- 2 回答
- 0 關注
- 121 瀏覽
添加回答
舉報