Using an array as a class member

This one may seem a bit weird, but what I want to do is use an array as a class member that is filed dynamically.

I’ve tried this, but it isn’t correct.

class testclass {
     public $testarray[] = array();

           public function __construct() {
                     $this->testarray[1] = 'new array entry';


Ideally I want to reference this as $mytestclass->testarray[1];

public $testarray = array();

class TestArray
    public $arr = array();
    public function __construct ()
        $this->arr[1] = 'new entry';

Alternative you could work with the ArrayAccess interface or extend from ArrayObject which would allow you to work with your object this:

class TestArrayAccess extends ArrayObject {}

$arr = new TestArrayAccess( range( 'a', 'z' ) );
var_dump( $arr[0], $arr[25] );
$arr['cat'] = 'goes meow';

var_dump( $arr );

What you did there “$testarray = array()” will actually make both $testarray and its first cell ($testarray[0]) arrays.

The way to define arrays in PHP is simply returning the results of the array() statement into a simple variable.