我知道这是一个语法错误,但我不知道我做了什么是错的。错误是
解析错误:语法错误,意外T_CONSTANT_ENCAPSED_STRING,期待T_STRING或T_VARIABLE或第8行的'{'或'$'
,代码是
class Person {
public $isAlive=true;
public $firstname;
public $lastname;
public $age;
public function __construct()
{
$teacher->"boring"=$firstname;
$teacher->"12345"=$lastname;
$teacher->12345=$age;
$student->"Natalie Euley"=$firstname;
$student->"Euley"=$lastname;
$student->19=$age;
}
public function greet()
{
return "Hello, my name is ".$this->firstname." ".$this->lastname. "Nice to meet you!";
}
}
$student = new Person();
$teacher = new Person();
echo $student->greet();
echo $techer->greet();
我现在明白了。 CodeAcademy有令人困惑的方向。我现在得到了怎么做。谢谢你解释一切!
答案 0 :(得分:4)
你应该这样做:
$teacher->"boring" = $firstname;
像这样:
$this->firstname = "boring";
对于你拥有其余代码的方式,你正在寻找的是这样的东西:
public function __construct($firstname, $lastname, $age)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->age = $age;
}
$teacher = new Person("John", "Smith", 45);
答案 1 :(得分:1)
您的语法不正确。
$this->firstname = "boring";
$this->lastname = "12345";
如果您要将这些值分配给您所在的班级,我们会使用“this”。
它是
$object->variable = value;
答案 2 :(得分:1)
这些是错误的
$teacher->"boring"=$firstname;
$teacher->"12345"=$lastname;
$teacher->12345=$age;
$student->"Natalie Euley"=$firstname;
$student->"Euley"=$lastname;
$student->19=$age;
应该是
$teacher->firstname = "boring";
$teacher->lastname = "12345";
$teacher->age = 12345;
$student->firstname = "Natalie Euley";
$student->lastname ="Euley";
$student->age = 19;
点击这里
答案 3 :(得分:1)
这样的东西:
$student->"Natalie Euley"=$firstname;
无效。可能你的意思是
$student->firstname = "Natalie Euley";
您不能使用"string"
作为对象键引用。但你可以使用:
$student->{"Natalie Euley"} = $firstname
^-- ^--note the brackets
然而,这仍然是倒退。这样的作业应该key => $value
,而你正在做$value => key
,这是低音的。
答案 4 :(得分:0)
构造函数方法中存在语法错误。例如,以下行不正确的PHP代码:
$student->"Natalie Euley"=$firstname;
我建议您阅读http://www.php.net/manual/en/language.oop5.php
上的官方文档根据您改进的代码示例工作正常:
class Person {
public $isAlive = true;
public $firstName;
public $lastName;
public $age;
public function __construct($firstName, $lastName, $age) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->age = $age;
}
public function greet() {
return 'Hello, my name is ' . $this->firstName . ' ' . $this->lastName .
' and I\'m '. $this->age . ' years old. Nice to meet you!';
}
}
$student = new Person('Max', 'Kid', 19);
$teacher = new Person('Albert', 'Einstein', 60);
echo $student->greet() . "\n";
echo $teacher->greet();