2017-08-24 45 views
-1

我有下一個代碼,我想要做的是保存並加載數組中的元素數量,並將它們顯示在我聲明爲show()的函數中,但是在我聲明函數內部的構造函數foreach 秀()我有一個錯誤如何從PHP7中的數組中獲取元素?

注意:未定義的變量:$ COMPLETE_NAME

,但如果我宣佈在功能相同的foreach保存,我得到正確的結果。

<?php 

class Person{ 

    public $name; 
    public $lastName; 

    public function save($name, $lastName){ 

     $COMPLETE_NAME = array(
      "NAME" => $name, 
      "LAST_NAME" => $lastName 
     ); 
    } 

    public function show(){ 
     foreach($COMPLETE_NAME as $list){ 
      echo $list; 
     } 
    } 

} 

$person = new Person(); 
$person->save("nameX", "last nameX"); 
$person->save("nameY", "last nameY"); 
$person->show(); 
?> 
+2

同所有PHP版本,使用你將失去的第二個名字:'$這個 - > COMPLETE_NAME' – AbraCadaver

+1

範圍問題[手冊應該幫助解釋](http://php.net/manual/en/language.variables.scope.php) – RiggsFolly

回答

0

其範圍界定問題,也可以作爲您將要覆蓋陣列以及

<?php 

class Person{ 
    // define the property as an array 
    public $names = []; 


    public function save($name, $lastName){ 
     // use $this to access the property 
     // also use [] as you call this more than once 

     $this->names[] = ["name" => $name,"lastname" => $lastName]; 
    } 

    public function show(){ 
     // foreach over outer array 
     foreach($this->names as $name){ 
      // echo from the inner array 
      echo $name['name'] . ' ' . $name['lastname']; 
     } 
    } 

} 

$person = new Person(); 
$person->save("nameX", "last nameX"); 
$person->save("nameY", "last nameY"); 
$person->show(); 
?> 
相關問題