tags:

views:

20

answers:

1

Hi I have set a property in a constructor like so

function __construct()
{

$this->count = count(@$_SESSION['filearray']); //count how many files in array
}

and using it in condition statements if($this->count > 10) //then do something

but it appears the count isn't being updated when I use another method of injecting values into this 'filearray' until I refresh the page.

am I doing something wrong? I thought that my constructor would detect a change had been made in the session and whenever I call $this->count I would get the current count value but it seems to be 1 step behind until I refresh the page.

If this is all vague I can include my form page that has all the method calls, but this is the jist of my question, why is my property not updating and how do I fix it :)

TIA

+2  A: 

$this->count won't automatically be updated with the count every time you add or subtract from the filearray session. Constructors are only invoked upon instantiation of the class or when called directly.

You can achieve this sort of functionality using a getter.

class myClass {
  public function getCount() {
    return count(@$_SESSION['filearray']);
  }
}

$_SESSION['filearray'] = array('bar');
$foo = new myClass();
echo $foo->getCount(); // 1

Or by using the __get() magic-method:

class myClass {

  public function __get($property_name) {
    if ($property_name == 'count') {
      return count(@$_SESSION['filearray']);
    }
  }
}

$_SESSION['filearray'] = array('bar');
$foo = new myClass();
echo $foo->count; // 1    

Or a combination of the two:

class myClass {

  private $_count;

  public function __get($property_name) {
    if ($property_name == 'count') {
      return $this->_getCount();
    }
  }

  private function _getCount() {
    return $this->_count = count(@$_SESSION['filearray']);
  }
}

$_SESSION['filearray'] = array('bar');
$foo = new myClass();
echo $foo->count; // 1
Mike B
thanks that did the trick mate, this is only my 2nd class I've written by myself so still understanding OOP :)
Jared