如何从PHP7中的数组中获取元素?

时间:2017-08-24 00:53:51

标签: php arrays

我有下一个代码,我想要做的是保存和加载数组中的元素数量,并在我声明 show()的函数中显示它们但是在我声明之后函数 show()中的构造函数foreach我有下一个错误

  

注意:未定义的变量:$ COMPLETE_NAME

但是,如果我在函数save中声明了相同的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();
?>

1 个答案:

答案 0 :(得分: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();
?>