March 4, 2012

Php, optional public variable

Question by Malixxl

i’ve some public variables in my class, here is how i define them

class MyClass
{
   public $var1;
   public $var2;
   public $var3;

   function __construct($params)
   {
     if(isset($params['var1']))
     $this->var1 = $params['var1'];

     if(isset($params['var2']))
     $this->var3 = $params['var2'];

     if(isset($params['var3']))
     $this->var3 = $params['var3'];

   }
}

but as i said theese are optional parameters. Some object’s will use it, some wont use it. My question is i’m defining it everytime even it’s used or not. Should i define it when it’s passed something like:

     if(isset($params['var1']))
     public $var1 = $params['var1'];

i’m quite newbie with php, just need to know what i’m doing at top is right?

edit:typo.

Answer by Sarfraz

You can create an array instead and store only those values that are submitted like this:

class MyClass
{
   public $data = array();

   function __construct($params)
   {
     if(isset($params['var1']))
        $this->data['var1'] = $params['var1'];

     if(isset($params['var2']))
        $this->data['var2'] = $params['var2'];

     if(isset($params['var3']))
        $this->data['var3'] = $params['var3'];

   }
}

This way you have a single concrete known variable you can refer to anytime to get needed data back.

Answer by Starx

I dont like the whole concept. Since you are defining a public variable, what is the entire point. Unless you are blocking this, we can easily initialize a public variable outside the class, like:

$obj = new classname();

$obj -> unknowpublicname = "somevaue";

Whatever you do, unless you restrict some rules, or change the access modifiers, it does not make any difference.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!