0

尽管我的代码符合 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";

为什么它不起作用?这实际上是输出,复制粘贴:

名称=$名称;} public function greet(){ print "我的名字是 {this->$name} 我很高兴!"; } } $foo=new Human("foo"); $bar=new Human("bar"); $foo->问候();$bar->问候();echo "程序完成"; ?>

4

3 回答 3

1

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

它应该是:

public function greet(){
    print "My name is {$this->name} and I am happy!";
}
于 2013-10-21T19:28:42.343 回答
1

您需要以 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!
}
于 2013-10-21T19:29:26.957 回答
1

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

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

经过

 print "My name is $this->name and I am happy!";
于 2013-10-21T19:30:54.490 回答