我正在为类做实验室工作,在使echo语句正常工作时遇到了一些问题。我试图将一个句子存储在对象中的一个变量中,然后检索并回显该变量的值。
<?php
class MagicSentence {
public $sentence;
public function __construct($sentence) {
$this->setSentence($sentence);
}
public function getSentence() { return $this->$sentence; }
public function setSentence($sentence) {
$this->sentence = $sentence;
}
} // End class MagicSentence
$magicSentence = new MagicSentence("The cow jumped over the moon.");
?>
<html>
<head>
<meta charset="utf-8">
<title>Pete's Treats Candy Contest</title>
</head>
<body>
<?php
//include ('header.php');
echo 'The magic sentence is: ' . $magicSentence->getSentence();
?>
</body>
</html>
应该是:
public function getSentence() { return $this->sentence; }
请注意sentence
上缺少$
。这只是PHP需要记住的一件事。