1

我正在学习 PHP 并阅读 Robin Nixon 的书。我在使用此代码时遇到问题:

<?php 
class Centre
{
    public $centre_name; // String: The name of the centre
    public $tagline; // String: The centre's tagline

        // Set the centres details. This will later be done through a form.
    function set_details()
    {
        $this->centre_name = "YMCA";
        $this->tagline = "Lets all go to the Y";
    }

        // Display the centres details. 
    function display()
    {
        echo "Centre Name - " . $centre->centre_name . "<br />";
        echo "Centre Tagline - " . $centre->tagline . "<br />";
    }
} 

?>

<?php 
    $centre = new Centre();
    $centre->set_details();
    $centre->display();
?>

现在这是输出:中心名称 - 中心标语 - 因此正在设置变量。我在使用 $this->variable = "whatever"; 正确吗?

4

3 回答 3

4

改变这个

function display()
{
    echo "Centre Name - " . $centre->centre_name . "<br />";
    echo "Centre Tagline - " . $centre->tagline . "<br />";
}

function display()
{
    echo "Centre Name - " . $this->centre_name . "<br />";
    echo "Centre Tagline - " . $this->tagline . "<br />";
}

您使用$centre而不是$this.

于 2013-02-20T09:37:27.673 回答
0

像这样更改您的函数 dispaly() :

在您的班级内,您可以使用以下方式访问变量$this

 function display()
    {
        echo "Centre Name - " . $this->centre_name . "<br />";
        echo "Centre Tagline - " . $this->tagline . "<br />";
    }
于 2013-02-20T09:38:03.770 回答
0

是的,但是在 display() 中用“this”替换“center”:

function display()
{
    echo "Centre Name - " . $this->centre_name . "<br />";
    echo "Centre Tagline - " . $this->tagline . "<br />";
}
于 2013-02-20T09:39:56.110 回答