PHP代码不会回显我的对象的属性

时间:2016-04-10 01:16:57

标签: php class echo setter getter

我正在上课的实验室,并且在使我的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>

1 个答案:

答案 0 :(得分:1)

应该是:

public function getSentence() { return $this->sentence; }

注意$上缺少sentence。关于PHP的其中一个要记住的事情。