在类中输入数组后没有返回任何内容

时间:2017-03-11 13:07:39

标签: php

我试图将值输入到类数组中,然后从类中输出该数组,但我从echo中得不到任何内容。谢谢你的建议。

<?php
class Packing{

    public $boxList;    
    public function getBoxlist() {
        return $boxList;
    }

    public function addBox($name,$weightLimit){
        $this->boxList = array($name, $weightLimit);
    }
}
?>

test

<?php
    $package = new Packing();
    $package->addBox("RedBox","30");
    $package->addBox("GreenBox","40");
    echo $package->getBoxlist();
?>

1 个答案:

答案 0 :(得分:4)

  1. 应该是这样,使用$this->boxList代替$boxList

    public function getBoxlist() {
      return $this->boxList;
    }
    
  2. 您正在覆盖boxList

  3. 其数组不是文字,因此请使用print_r而不是echo

    print_r($package->getBoxlist());
    
  4. 点击此处:https://eval.in/752903

    来自https://eval.in/752907

    的演示
    <?php
    class Packing{
    
        public $boxList =  array();    
        public function getBoxlist() {
            return $this->boxList;
        }
    
        public function addBox($name,$weightLimit){
            $this->boxList[] = array($name, $weightLimit);
        }
    }
        $package = new Packing();
        $package->addBox("RedBox","30");
        $package->addBox("GreenBox","40");
        print_r($package->getBoxlist());
    ?>