【发布时间】: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