我正在实现一个PHP(5.4.4)类,用于包含用于HTML渲染的类定义(以动态方式),因此如果我有一个带有两个按钮,四个文本输入和一个复选框的表单,我只包含对应于表单,文本框和按钮的.php文件,而不是其他任何东西(每个HTML对象都用一个类表示)。
但是我有一个问题...我创建了一个名为 ComponentManager 的类来管理加载过程,代码如下:
class ComponentManager {
// component manager properties
protected $components;
// constructor for this object
public function __construct() {
if (!empty($_SESSION['components'])) {
$this->components = explode(" ", $_SESSION['components']);
} else {
$this->components = null;
}
}
// destructor for this object
public function __destruct() {
$this->components = null;
}
// getter for this object
public function __get($property) {
if ($property === "components") {
return $this->components;
}
}
// addComponents - add components to the current components list
public function addComponents($components) {
if (!empty($components)) {
$list = explode(" ", $components);
$count = sizeof($list);
for ($i = 0; $i < $count; $i++) {
if (!in_array($list[$i], $this->components)) {
$this->components[] = $list[$i];
$component = null;
问题是我似乎无法使用 in_array() 函数,我不知道为什么......我的意思是,我过去曾多次使用它来做不同的事情,但一直告诉我:
警告:in_array() 期望参数 2 是数组,在第 34 行的 D:''apache''htdocs''webapps''skeleton''assets''scripts''manager.php 中给出 null
我将测试代码中的$components作为空格分隔的列表传递,如下所示:
$page->addComponents("form checkbox textbox button range number");
我的目的是指定:如果组件列表不为空,给我一个包含输入组件的数组,对于每个组件,当且仅当组件数组中尚不存在时插入它。
我做错了什么?
显然,您的构造函数启动$this->components
null
,然后您尝试通过 addComponents()
访问它。
您可能打算启动它以$this->components = array();
,以便列表以空数组开始,从而允许您在其上使用in_array()
?