1

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.

1
  • it should as simple as $c->$v[product]="new key" Commented Jan 18, 2014 at 6:07

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Both of you gave me the answer but you answered first =] Thanks.
3

You can change public class property by class object like this:

Live Demo : https://eval.in/91444

class license
    {

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

     }

     $c = new license;
     $c->v['product'] = "new values";
     echo $c->v['product'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.