0

so i'm having a php class like the following:

class myClass
{
    function __construct()
    {
        $this->chart_data = array(1,2,3,4,5);
        $this->captions   = array("a", "b", "c", "d", "e");
    }
}

is there a way to access the properties the same way like an associative array, like:

$obj = new myClass();
echo $obj['chart_data'];
echo $obj['captions'];

thanks!

Fuxi
  • 7,611
  • 25
  • 93
  • 139
  • 1
    possible duplicate - [http://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array](http://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array) – shatheesh Jun 11 '14 at 06:51
  • 1
    There is an interface for that: http://php.net/ArrayAccess Implement its methods, and you're ready to go... – Fracsi Jun 11 '14 at 06:51
  • that's what i've been looking for - thanks fracsi – Fuxi Jun 11 '14 at 06:52

2 Answers2

1

you can try

echo $obj->{'chart_data'};
echo $obj->{'captions'};
Sooraj Tom
  • 11
  • 1
  • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. – Tom Aranda Dec 16 '17 at 06:33
0

From this answer you can try like this

$obj = (array) new myClass();
print_r($obj);
Community
  • 1
  • 1
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91