我正在学习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 />";
}