【问题标题】:How to call and view an array in a function如何在函数中调用和查看数组
【发布时间】:2014-03-26 15:38:43
【问题描述】:

我是 PHP 和 Kohana 的新手。 我想知道如何在函数中调用数组。

我有变量 $productlist,我想通过函数向其中添加更多元素。

public $productlist =  array();
public function action_index()
{
   $product = new Product("Laptop","HP4897");
   $product2 = new Product("TV","Samsung 8773");


   $productlist[] = product;
   $productlist[] = product2;

   $this->add_product_to_array("Ebook","Everything you want to know");
   $this->show_productlist();
}

public function add_product_to_array($product_name, $product_description)
{
    $newproduct = new Product($product_name, $product_description);
    array_push($productlist,$newproduct);
}
public function show_productlist(){
    foreach($productlist as $key => $value)
    {
        print_r($value->get_product_name().'</br>');
    }
}

这是我得到的例外: *ErrorException [ 警告 ]: array_push() 期望参数 1 是数组,给定 null*

如果我添加 foreach($this->productlist as $key => $value),它会告诉我找不到 productlist。

产品.php

class Product {

private $_product_name;
private $_product_description;


function __construct($name,$description)
{
    $this->_product_name = $name;
    $this->_product_description = $description;
}

public function get_product_name()
{
    return  $this->_product_name;
}
//etc

【问题讨论】:

  • 这些函数(add_product_to_array 等)是类的一部分吗?如果是这样,那么您可以在任何函数中将产品列表称为 $this->productlist。如果没有,那么您应该考虑为它们创建一个类。

标签: php arrays function loops foreach


【解决方案1】:

PHP Classes and Objects - The Basics

在类内部访问$productlist数组时需要使用$this-&gt;productlist。您似乎在Product 课程中知道这一点。发生了什么?

【讨论】:

  • 我在我的代码中某处不属于那里的 $ 失败了。感谢您指出 $this->productlist.. 我有 $this->$productlist.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
相关资源
最近更新 更多