虽然我的代码符合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->迎接(); $酒吧,>迎接(); echo“程序完成”; ?>
答案 0 :(得分:1)
从类的代码中访问对象的属性时,需要使用$this
。您从$name
内部访问了Human
greet()
的{{1}}属性,但您错过了$this
。
应该是:
public function greet(){
print "My name is {$this->name} and I am happy!";
}
答案 1 :(得分: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!
}
答案 2 :(得分:1)
问题在于您使用name作为变量而不是类成员。您需要使用$this
关键字。
print "My name is $name and I am happy!";
通过
print "My name is $this->name and I am happy!";