我目前在Codecademy上学习PHP,在课堂上遇到一个错误,我不知道为什么。我得到这个错误Undefined variable: name (line 21)Woof, woof! !
。PHP中未定义的变量与类
这里是我的代码:
<?php
class Dog {
public $numLegs = 4;
public $name;
public function __construct($name){
$this->name = $name;
}
public function bark(){
return "Woof!";
}
public function greet(){
return "Woof, woof! ".$name."!";
}
}
$dog1 = new Dog("Barker");
$dog2 = new Dog("Amigo");
$dog1->bark();
echo $dog2->greet();
?>
它在这一课http://www.codecademy.com/courses/web-beginner-en-ZQQ64/0/8#。谢谢你的帮助。 :)
这是一个范围的问题 - '$中的name'迎接'()'函数是一个局部变量,这是没有定义的;因此警告。您可能需要'$ this-> name' – andrewsi