dpgui8229808 2016-08-08 05:58
浏览 27
已采纳

在两个不同的类中引用相同的变量

<?php

class Foo{
    public $basket;

    public function __construct()
    {
        $this->basket = 1;
    }

    public function getBasket(){
        return $this->basket;
    }
}

class Bar{
    public function __construct(&$basket)
    {
        $basket++;
    }
}

$newFoo = new Foo();
$newBar = new Bar($newFoo->getBasket());

echo $newFoo->getBasket();

?>

I am hoping to initialise the $basket value in one class and manipulate the same variable via another class. Unfortunately, I keep getting the "Notice: Only variables should be passed by reference in " error message.

Question: How can I change the code to make this happen? Thank you.

  • 写回答

1条回答 默认 最新

  • duanmou9228 2016-08-08 06:00
    关注

    Change

    $newBar = new Bar($newFoo->getBasket());
    

    To

    $basket = $newFoo->getBasket();
    $newBar = new Bar($basket);
    

    The first way doesn't work because PHP doesn't have any variable with which to hold the value you're passing to new Bar() As a consequence, nothing can be passed by reference.

    The second way works because the $basket var is a fixed reference in memory, so it can be passed by reference to new Bar()

    You asked in comments:

    have changed my code to yours. echo $newFoo->getBasket(); produces 1 (I was hoping for 2).

    1 is produced because each call to getBasket() gives you a fresh copy of the class variable. The $basket that I passed to new Bar() equals 2, but that's not what you're echoing.

    If you want the result of getBasket() and the variable $basket to refer to the same reference in memory, you need to make two changes:

    1 Change the function declaration to:

    public function &getBasket()
    

    2 Change how you store the function result to:

    $basket = &$newFoo->getBasket();
    

    Now your echo will return 2 because you would have a unique basket reference throughout your code

    See the docs

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案