开发者

PHP : create variable dynamically

I have one of my class method like this shown below :

public function somethin开发者_如何转开发g() {
    $this->create_varible('test');
    return $test;
}

I wanna create some variable(not class variable) by passing it's name as argument to create variable method(as shown above), then return it's value.

your help will be appreciated, thanks in advance.


Example:

<?php

public function create_variable($name, $value) {
  // Dynamically create the variable.
  $this->{$name} = $value;
}

Or:

<?php

$stack = 'overflow';
${$stack} = 'example';

echo $overflow;

Please keep in mind the scope of variables.


I don't see the point in that either. But to answer your question literally:

You can use extract for that purpose:

public function something() {
    extract($this->create_varible('test'));
    return $test;
}

public function create_varible($varname) {
    return array ($varname => 12345);
}

The ->create_varible by itself cannot create a variable in the invokers scope. That's why you need to wrap the call in extract() to get something like the desired effect; whatever its purpose.

(Yes, aware of the typo.)


How about using PHP's Magic Methods, specifically the __get and __set methods.

class Foo
{
  public function __set($varName, $value)
  {
    $GLOBALS[$varName] = $value;
  }
  public function __get($varname)
  {
    return isset($GLOBALS[$varName]) ? $GLOBALS[$varName] : null;
  }
}

$foo = new Foo();
$foo->test = "Bar";
echo $test; // output: Bar

Demo found here: http://www.ideone.com/nluJ5

P.S. I mention this because if your use of $this->, and assume you're dealing with objects.

P.P.S. I think @Francois has the better solution, but offering another alternative.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜