douban5644 2012-03-14 15:08
浏览 66
已采纳

php,变量by ref或value

I've read this (References Explained), this stackoverflow (I say this to avoid duplicates and to show I've googled a lot before posting) and I still don't understand how to implement a very simple thing.

Here's what I want to do:

  • class Products
  • class Product

All with getter / setter.

I have a page that will construct dynamically an array of products, a group of products, then I'll create new products, and add them to that group:

<?php

$group_of_products = new Products();
$product1 = new Product();
$product1->setName("name1");
$product2 = new Product();
$product2->setName("name2");
$product3 = new Product();
$product3->setName("name3");

$group_of_products->addProduct($product1);
$group_of_products->addProduct($product2);
$group_of_products->addProduct($product3);

?>

Now here's what I want:

<?php

$group_of_products->getProduct( 0 )->setName("NewName1");
$group_of_products->getProduct( 1 )->setName("NewName2");
$group_of_products->getProduct( 2 )->setName("NewName3");

echo $product1->getName().", ";
echo $product2->getName().", ";
echo $product3->getName();

?>

And I'd like to see NewName1, NewName2, NewName3.

How should I declare the function addProduct() of the class Products to obtain such behavior?

  • 写回答

2条回答 默认 最新

  • doudang2817 2012-03-14 15:11
    关注

    You shouldn't need to pass things by reference. Here is an example that should work:

    class Products
    {
        private $products, $count = 0;
        function getProduct( $i)
        {
            return isset( $this->products[$i]) ? $this->products[$i] : null;
        }
    
        function addProduct( $product)
        {
            $this->products[$this->count++] = $product;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法