php$this->函数中的变量没有像我希望的那样工作



我正在学习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";正确地

更改此

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

像这样更改函数dispay():

在您的类中,您可以使用$this 访问变量

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

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

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

相关内容

最新更新