0

我目前正在 Codecademy 上学习 PHP,但我在他们的课程中遇到了一个错误,我不知道为什么。我得到这个错误Undefined variable: name (line 21)Woof, woof! !

这是我的代码:

<?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#。谢谢你的帮助。:)

4

2 回答 2

6

为了引用类字段,您需要使用$this->. 所以这一行:

return "Woof, woof! ".$name."!";

应该是这样的:

return "Woof, woof! ".$this->name."!";
于 2013-06-19T16:32:13.723 回答
3

它告诉你 - 在第 21 行,$name没有定义。你的意思是$this->name

于 2013-06-19T16:32:12.570 回答