property not updating in object when page is posted
I have set a property in a constructor like so
function __construct()
{
$this->count = count(@$_S开发者_如何学CESSION['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
$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
精彩评论