虽然我的代码使用了正确的语法,但我的代码无效[关闭]

My code isn't working although it conforms with PHP syntax.

$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";

Why isn't it working? This is literally the output, copy-pasted:

name=$name; } public function greet(){ print "My name is {this->$name} and I am happy!"; } } $foo=new Human("foo"); $bar=new Human("bar"); $foo->greet(); $bar->greet(); echo "The program is done"; ?>

When accessing properties of an object from inside the class's code you need to use $this. You accessing the $name property of Human from inside greet() but you are missing the $this.

It should be:

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

You need to start your PHP code with <?php to show that it is PHP code, not just plain text.

Its not valid syntax $name is not defined in this scope:

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

Since $name is a member of the class not the function you need to use $this

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

The problem is that you are using name as a variable instead of a class members. You need to use the $this keyword.

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

by

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