php输出构造函数数组

时间:2018-06-08 03:22:52

标签: php arrays

我尝试执行下面的代码来输出数组中的每个值,结果显示结果:

Notice: Array to string conversion in C:\xampp\htdocs\test\tutor.php on line 22
_data : Array

PHP

<?php
class CateData 
{
    private $_data = array();

    public function __construct($data){

        $this->_data = $data;
    }
}

$data = array(
            'a'=>'Cate1',
            'b'=>'Cate2',
            'c'=>'Cate3',
            'd'=>'Cate4'
        );

$cate = new CateData($data);

foreach($cate as $key => $val){
    echo $key." : ". $val;
}
?>

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

您正在循环使用类对象而不是实际数据。

在你的班级中添加:

public function getData(){
   return $this->_data;
}

然后更改:

foreach($cate as $key => $val){
    echo $key." : ". $val;
}

foreach($cate->getData() as $key => $val){
    echo $key." : ". $val;
}

答案 1 :(得分:0)

首先,您应该清除public protectprivate之间的差异。

在您的代码中,您应该将_data更改为公开,因为您想要在课堂外访问。

然后改变:

foreach($cate as $key => $val){
    echo $key." : ". $val;
}

为:

foreach($cate->_data as $key => $val){
    echo $key." : ". $val;
}

答案 2 :(得分:0)

虽然接受的答案更好,但另一种方法是更改​​范围,这样您就不需要添加getData()方法。但是可以直接访问类变量。

//将变量更改为public,并循环$cate->_data

class CateData 
{
    public $_data = array();

    public function __construct($data){

        $this->_data = $data;
    }
}

$data = array(
            'a'=>'Cate1',
            'b'=>'Cate2',
            'c'=>'Cate3',
            'd'=>'Cate4'
        );

$cate = new CateData($data);


foreach($cate->_data as $key => $val){
    echo $key." : ". $val;
}