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?

1
  • Please read up on the basics of OOP. Commented Jun 8, 2018 at 3:39

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

No, it would be better practice you use a getter function as suggested by the accepted answer. No need to mess with the visibility.
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;
}

1 Comment

Please format your code properly and why should they change the visibility of the property? A getter would be better as suggested by the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.