我的代码不起作用,尽管它使用了正确的语法


My code isn't working although it uses correct syntax

我的代码不起作用,尽管它符合PHP语法。

$x=200;
$y=100;
class Human {
    public $numLegs=2;
    public $name;
    public function __construct($name){
        $this->name=$name; // The PHP stops being parsed as PHP from the "->"
    }
    public function greet(){
        print "My name is $name and I am happy!"; // All of this is just written to the screen!
    }
}
$foo=new Human("foo");
$bar=new Human("bar");
$foo->greet();
$bar->greet();
echo "The program is done";

为什么它不起作用?从字面上看,这是复制粘贴的输出:

名称=$name; }公共函数 greet(){ print "My name is {this->$name} and I am happy !"; } }$foo=新人类("foo");$bar=新人类("酒吧");$foo->greet();$bar->greet();echo "程序已完成"; ?>

从类的代码内部访问对象的属性时,需要使用 $this .您从内部访问Human$name属性greet()但缺少$this

它应该是:

public function greet(){
    print "My name is {$this->name} and I am happy!";
}
你需要

<?php开始你的PHP代码,以表明它是PHP代码,而不仅仅是纯文本。

其无效语法$name未在此范围内定义:

public function greet(){
    print "My name is $name and I am happy!"; // All of this is just written to the screen!
}

由于$name是类的成员,而不是您需要使用的函数$this

public function greet(){
    print "My name is {$this->name} and I am happy!"; // All of this is just written to the screen!
}

问题是你使用 name 作为变量而不是类成员。您需要使用 $this 关键字。

 print "My name is $name and I am happy!";

 print "My name is $this->name and I am happy!";