0

I want to create properties in a class with the names of all of the variables passed to the constructor and with the same values.

I was able to do it with strings:

class test {

    public function __construct() {
        $args = func_get_args();
        foreach($args as $arg) {
            $this->{$arg} = $arg;
            $this->init();
        }
    }

    public function init() {
        echo $this->one;
    }
}

// Output: "one"
$obj  = new test("one");

But I don't know how I can do it with variables. I tried this:

class test {

    public function __construct() {
        $args = func_get_args();
        foreach($args as $arg) {
            $this->{$arg} = $arg;
            $this->init();
        }
    }

    public function init() {
        echo $this->one;
    }
}

$one  = "one!";
$obj  = new test($one);

Output:

Notice: Undefined property: test::$one on line 13

What I wanted it to output:

one!
James
  • 261
  • 2
  • 5
  • 16

2 Answers2

0

Try:

public function init() {
   echo $this->{'one!'};
}
Fven
  • 547
  • 3
  • 5
0

No, it's not possible in any sane way to get the name of a variable used in calling code inside the callee. The sanest method is to use new test(compact('one')), which gives you a regular key-value array inside test::__construct, which you can loop through.

http://php.net/compact

deceze
  • 510,633
  • 85
  • 743
  • 889