我在构造函数中设置了一个属性,如此
function __construct()
{
$this->count = count(@$_SESSION['filearray']); //count how many files in array
}
并在条件语句if($this->count > 10) //then do something
但是当我在刷新页面之前使用另一种将值注入到'filearray'中的方法时,似乎没有更新计数。
我做错了什么?我认为我的构造函数会检测到会话中发生了更改,每当我调用$ this-> count时,我会得到当前的计数值,但在刷新页面之前它似乎落后了一步。如果这一切都模糊,我可以包含我的表单页面,其中包含所有方法调用,但这是我的问题的主旨,为什么我的属性不更新,我该如何修复它:)
TIA
答案 0 :(得分:2)
$this->count
都不会自动更新计数。只有在实例化类或直接调用时才会调用构造函数。
您可以使用getter实现此类功能。
class myClass {
public function getCount() {
return count(@$_SESSION['filearray']);
}
}
$_SESSION['filearray'] = array('bar');
$foo = new myClass();
echo $foo->getCount(); // 1
或者使用__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
或两者的结合:
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