Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 发布页面时对象中的属性未更新_Php_Oop - Fatal编程技术网

Php 发布页面时对象中的属性未更新

Php 发布页面时对象中的属性未更新,php,oop,Php,Oop,我在构造函数中设置了一个属性,如下所示 function __construct() { $this->count = count(@$_SESSION['filearray']); //count how many files in array } 在条件语句if($this->count>10)//中使用它,然后做一些事情 但在刷新页面之前,当我使用另一种方法将值注入此“filearray”时,计数似乎不会被更新 我做错什么了吗?我以为我的构造函数会检测到会话中发生的更改,每当我调

我在构造函数中设置了一个属性,如下所示

function __construct()
{

$this->count = count(@$_SESSION['filearray']); //count how many files in array
}
在条件语句
if($this->count>10)//中使用它,然后做一些事情

但在刷新页面之前,当我使用另一种方法将值注入此“filearray”时,计数似乎不会被更新

我做错什么了吗?我以为我的构造函数会检测到会话中发生的更改,每当我调用$this->count时,我都会得到当前的计数值,但在刷新页面之前,它似乎落后了1步

如果这一切都是模糊的,我可以包括我的表单页面,其中包含所有的方法调用,但这是我的问题的jist,为什么我的属性没有更新,我如何修复它:)


TIA

$this->count
不会在每次添加或减去filearray会话时自动更新计数。构造函数仅在类实例化时或直接调用时调用

您可以使用getter实现这种功能

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

$_SESSION['filearray'] = array('bar');
$foo = new myClass();
echo $foo->getCount(); // 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

请注意,使用
@
运算符是一种糟糕的形式,也是一种性能损失。尝试
array\u key\u exists('filearray',$\u SESSION)&&is\u array($\u SESSION['filearray'])?计数($\u会话['filearray']):0
--它更详细,但它没有
@
操作符隐藏的警告和通知。感谢您的提示Charles,我尽量不使用“@”,但有时我会因为我所做的工作规模而懒惰。但无论如何,很高兴知道,有人需要制作一本php技巧手册:)/me返回谷歌感谢做了技巧助手,这只是我自己写的第二节课,所以仍然理解OOP:)
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