Results 1 to 3 of 3

Thread: ArrayAccess not storing info?

  1. #1
    Join Date
    Jun 2010

    ArrayAccess not storing info?

    I'm trying to learn more about using the ArrayAccess interface.

    I have one class (UserClass) creating an object that implements ArrayAccess (MyRecords). There is an array defined in UserClass that I wish to add to Records. For example, in UserClass:

    $records_array = array ('name' => 'Bob', 'age' => '26');
    $myRecords = new MyRecords();
    $myRecords->offsetSet (0, $records_array);
    The $records_array is getting passed into offsetSet but the problem is that the data passed into it isn't getting saved in the myRecords instance. The var_dump in offsetSet actually prints out the values defined in $records_array. In MyRecords:

       private $data = array();
       public function offsetSet ($offset, $value) {
          if (!is_numeric($offset)) {
             throw new Exception ("Key must be numeric");
          else {
             $this->data[$offset] = $value;
             var_dump ($value);
    Any idea why why the data isn't getting saved in MyRecords::data ??

  2. #2
    Join Date
    Jul 2010
    Quote Originally Posted by dukesdemise View Post
    ... Any idea why why the data isn't getting saved in MyRecords::data ??
    :: as in static? Because the way you are declaring $data is not static.

    PHP Code:
    private $data = array();
    $this->data[$offset] = $value
    Also private implies that MyRecords::$data is 100% the incorrect way to access such a variable. Private means it can only be seen while inside of that class's scope, and when you're in such a scope you would use self::$data and NOT MyRecords::$data. Although both will work (i think) as long as you're inside of the class. In other words UserClass can't see MyRecords::$data without using a getRecords() type function.

    Your code snippets look fine, I'm even tickled that you knew to throw an exception should someone try and pass NULL as an argument for $offset.

    You'll need to post more code (a test case) to be sure. Even better would be to make a unit test- (which is reusable! if you ever decide to modify your class's code). Unit testing sounds really really lame, but it's incredible- it's almost cheating actually. It will find your problems that you may have never even known existed or were even possible or have gone overlooked for months.
    I use (, ; : -) as I please- instead of learning the English language specification: I decided to learn Scheme and Java;

  3. #3
    Join Date
    Jun 2010
    Thanks eval. What I was trying to do was ok, but I wasn't retrieving the data properly so it appeared to be empty (to me).

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center