2014-02-10 145 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(); 
相關問題