donglang1894 2014-01-18 06:03
浏览 5
已采纳

php - 在另一个类实例中更改值数组

I am playing around with some php, and I found myself wondering something.

    <?php

class license
{

    public $v=array('product'=>"babab");
    function blah($b)
    {
        if (//code)
        {
            //code
        }
    }

Is there a way to change the values of the array in another instance of the class?

For example...

    $c = new license;
    //change $v values??
    $c->blah('woof.php');

How can I change the value of product in the $v array there?

I hope I was clear.

  • 写回答

2条回答 默认 最新

  • douzhang1364 2014-01-18 06:06
    关注

    Since you declared it as public, anyone can write to it that has an instance of the class.

    $c->v = array('key', 'value');
    

    You could change it to any data type you want.

    $c->v = new MyObject();
    $c->v = NULL;
    $c->v = FALSE;
    $c->v = 1;
    

    But if you are saying that you want to create an additional license object and be able to change the value of your property, you wouldn't be able to with your existing architecture. The singleton design pattern solves this.

    class License {
      private static $instance;
      private $v;
      private function __construct() {}
      private function __clone() {}
    
      public static function getInstance() {
        if(!isset(self::$instance)) {
          self::$instance = new static();
        }
        return self::$instance;
      }
      public function setV($data) {
        $this->v = $data;
      }
      public function getV() {
        return $this->v;
      }
    }
    
    $license = License::getInstance();
    $license->setV(array("key" => "value"));
    var_dump($license->getV());
    
    $license2 = License::getInstance();
    var_dump($license == $license2);
    // true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大