PHP 代码不会回显我对象的属性
PHP code will not echo out the attribute of my object
我正在为 class 做一个实验,在让我的 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 的事情之一要记住。
我正在为 class 做一个实验,在让我的 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 的事情之一要记住。