2014-02-10 147 views
0

我知道这是一个语法错误,但我没有看到我做了什么错。该错误是我不明白为什么我得到这个错误

Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting T_STRING or T_VARIABLE or '{' or '$' on line 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有混乱的方向。我现在得到如何去做。感谢您解释一切!

+2

你的类成员变量赋值是无效的语法。事实上,他们倒退了。我以前从来没有见过。 –

+0

它是一个令人印象深刻的错误尝试 – 2014-02-10 19:08:11

+1

@Dagon:这是怎样的建设性?每个人都曾经是初学者,并且**人不是天生就知道PHP及其语法**。我同意这实际上是一个低质量的问题,但我个人觉得这样的评论是粗鲁/有害的,并且具有零关联性。 –

回答

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

您的语法错误。

$this->firstname = "boring"; 
$this->lastname = "12345"; 

我们用 “这个” 如果你是这些值分配给类,你都英寸

它去

$object->variable = value; 
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; 
0这里

检查

http://www.php.net/manual/en/language.oop5.php

1

这样的东西:

$student->"Natalie Euley"=$firstname; 

无效。也许你的意思是

$student->firstname = "Natalie Euley"; 

您不能使用"string"像一个对象重要的参考。但你可以使用:

$student->{"Natalie Euley"} = $firstname 
      ^--    ^--note the brackets 

但是,这仍然是倒退。像这样的分配应该完成key => $value,而你正在做$value => key,这是低音赞赏。

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(); 
相关问题