关于 PHP 中类变量的建议


Advice upon class variables in PHP

我在调用我的$dog2方法时显示错误greet()这是未定义的变量,但我无法理解我在哪里犯了错误。请帮我:)

 <?php
        class Dog{
            public $numLegs=4;
            public $name;
            public function __construct($name){
                $this->name=$name;
            }
            public function bark(){
                return "woof";
            }
            public function greet(){
                return $name." is very beatifull dog hmmm";
            }
        }
        $dog1= new Dog("Barker");
        $dog2= new Dog("Amigo");
        echo $dog1->bark();
        echo $dog2->greet();

    ?>

你不能像$name那样直接访问名称,你必须使用$this->name

更改以下行

 return $this->name." is very beatifull dog hmmm";

$this->name引用当前类的变量名,使用 $this->name 时,您正在使用当前对象的名称访问属性。