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 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数