1

I tried executing the code below to output each value from an array, end up result show:

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;
}
?>

How can I solve this?

Script47
  • 14,230
  • 4
  • 45
  • 66
Ben Koo
  • 79
  • 1
  • 7

3 Answers3

4

You're looping on the class object and not on the actual data.

In your class add:

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

Then change:

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

To:

foreach($cate->getData() as $key => $val){
    echo $key." : ". $val;
}
Karlo Kokkak
  • 3,674
  • 4
  • 18
  • 33
0

First you should clear the differences between public protect and private.

In your code, you should change your _data to public because you want to visit outside your class.

Then change:

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

to:

foreach($cate->_data as $key => $val){
    echo $key." : ". $val;
}
JustBaron
  • 2,319
  • 7
  • 25
  • 37
clearT
  • 1
  • Please format your code properly and why *should* they change the visibility of the property? A [getter](https://stackoverflow.com/a/8955492/2263631) would be better as suggested by the accepted answer. – Script47 Jun 08 '18 at 03:43
0

While the accepted answer is better, an alternative is to change the scope so you you dont need to add a getData() method. But can then access the class variables directly.

//change the variable to public, and loop $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;
}
  • No, it would be better practice you use a [getter](https://stackoverflow.com/questions/4478661/getter-and-setter/8955492#8955492) function as suggested by the accepted answer. No need to mess with the visibility. – Script47 Jun 08 '18 at 03:53