【问题标题】:use a class as array element使用类作为数组元素
【发布时间】:2014-05-28 17:13:29
【问题描述】:

我有多个包含字符串的文件。我使用文本分隔符将字符串分成几行。我使用另一个文本分隔符将每一行分成字段

我正在使用多个类来执行此操作。我有一个需要多次实例化的类(行类),所以我想要一个此类的数组。当我收到一条消息说我不能将该对象用作数组时,我遇到了障碍。你能提供任何建议吗?这是错误消息和我的代码

致命错误:无法在第 20 行使用 lineController 类型的对象作为数组`

<?php
require_once('/super_src/controller/fileController.php');
require_once('/super_src/controller/lineController.php');
require_once('/super_src/controller/elementController.php');
require_once('/super_src/controller/exceptionController.php');

class masterControl{
public $fc;//fileControl variable
public $lc = array();//lineControl variable
public $ec;//elementControl variable
public $xc;//exceptionControl variable

public function __construct(){
    $this->fc = new fileController($this->path);
}

public function setLC($lc){$this->lc = $lc;}//end setLC()

//I get the error on this line where I have lc[$index]
public function setLCAtIndex($value, $index){$this->lc[$index] = $value;}//end setLCAtIndex()
public function getLC(){if($this->lc == null) return "";else return $this->lc;}//end getLC()
public function getLCAtIndex($index){if($this->lc == null && $this->lc != 0) return "";else return $this->lc[$index];}//end getLCAtIndex()


public function ediTeardown(){
    $this->fc->searchFiles($this->fc->getPath());//the files
//      var_dump($this->fc->getFile());
    $index = 0;
    foreach($this->fc->getFile() as $file){
        $this->lc = new lineController();
        $this->lc->extractLines($file);
        $this->setLCAtIndex($file, $index);
        $index++;
    }//end foreach()
}//end ediTeardown()

public function echoArray($array){foreach ($array as $a){echo $a."-";echo"<br>";};}
public function __toString(){}
}

$mc = new masterControl();
$mc->ediTeardown();
//var_dump($mc->getLC());
echo "<br><br><br><br><br><br>End Of Line!"
?>

【问题讨论】:

    标签: php arrays class instantiation


    【解决方案1】:

    在你的代码的第 30 行

    $this->lc = new lineController();
    

    这正在将您的“$this->lc”变量从数组更改为对象。

    如果您想创建一个 lineController 的数组,您应该将该行更改为:

    $tmp_lc = new lineController();
    $tmp_lc->extractLines($file);
    $this->lc[] = $tmp_lc;
    

    编辑:

    要获得更简洁的解决方案,您的代码应如下所示:

    $num_lc = 0;
    foreach($this->fc->getFile() as $file){
        $this->lc[$num_lc] = new lineController();
        $this->lc[$num_lc]->extractLines($file);
        $this->setLCAtIndex($file, $index);
        $index++;
        $num_lc++;
    }//end foreach()
    

    使用此代码,您无需设置大型结构的临时变量,您可以使用计数器作为数组位置,并直接写入数组。

    【讨论】:

    • 不客气,我很高兴能帮上忙。如果您想要一个更简洁的解决方案(没有辅助变量),请告诉我,我将编辑答案以包含该解决方案。
    • 哦,那也太棒了,我很想看看
    • 我添加了更清洁的解决方案。由于删除了临时 lc 变量,它应该比第一个解决方案使用更少的 RAM。另一方面,您应该将类​​变量设为私有或受保护,因为您已经拥有 get 和 set 方法(至少对于 $lc 变量而言)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2014-04-06
    • 2011-05-12
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多