1

I want to declare a variable inside a class with an unknown name

class Example {
    function newVar($name, $value) {
        $this->$name = $value;
    }
}

And I want to use it that way

$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->MyVariableName);

The Important thing is, that I do not know the name of the variable. So I cannot put a public $MyVariable inside the class.

Is that in anyway possible? and if yes, can i do this with different scopes (private, protected, public) ?

Doug
  • 547
  • 10
  • 23
TheEquah
  • 121
  • 8

3 Answers3

1

If i am understanding this correctly you can tweak a little bit by using key value array

class Example {
    private $temp;

    function __construct(){
       $this->temp = array();
    }
    function newVar($name, $value) {
        $this->temp[$name] = $value;
    }
    function getVar($name){
        return $this->temp[$name];
    }
}
$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->getVar('MyVariableName'));

Instead of using private you can use protected as well.

Tom
  • 81
  • 5
1

U should use magic methods __get and __set (example without checking):

class Example { 
   private $data = [];

   function newVar($name, $value) {
      $this->data[$name] = $value;
   }

   public function __get($property) {
        return $this->data[$property];
   }

   public function __set($property, $value) {
        $this->data[$property] = $value;
   }       
 }


$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->MyVariableName); 
// This is my Value

$c->MyVariableName = "New value";
echo($c->MyVariableName);
// New value

See http://php.net/manual/en/language.oop5.magic.php

voodoo417
  • 11,861
  • 3
  • 36
  • 40
  • There is no need for the `newVar()` method, `$c->MyVariableName = "New value";` would suffice for both instantiation and reassignment. – samrap Sep 15 '15 at 22:20
  • I was just clarifying for the OP. The current example makes it seem like you have to first use the `newVar()` method to instantiate the "property" – samrap Sep 15 '15 at 22:23
0

Your looking for magic calling. In PHP you can use the __call() function to do stuff like that. Have a look here: http://www.garfieldtech.com/blog/magical-php-call

Off the top of my head, something like

function __call($vari, $args){
    if(isset($this->$vari){
        $return = $this->$vari;
    }else{
        $return = "Nothing set with that name";
    }
}

This will also work for private, protected and public. Can also use it to call methods as required in a class

Doug
  • 547
  • 10
  • 23
  • the `__call` magic method is used to call dynamic methods, not to set properties. Please have a look at http://php.net/manual/en/language.oop5.overloading.php – samrap Sep 15 '15 at 22:18