开发者

$this->"variable value" OOP PHP

I'm wondering if it's 开发者_如何学JAVApossible, and in case it is, how shoud I achive that:

$this->id <-- i have such thing. but to make it more usable i'd like to have $this->(and here to change the values)

for ex: I might have $this->id $this->allID $this->proj_id

how can I make so that actually I have $this->($myvariable here, that has a unique name in it)?


You can simply use this:

 $variable = 'id';
 if ( isset ( $this->{$variable} )  ) 
 {
    echo $this->{$variable};
 }


Here is the solution : http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

An example of using it is here :

class myClass {
    /**  Location for overloaded data.  */
    private $myProperties = array();

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

    public function __get($name)
    {
        if (array_key_exists($name, $this->myProperties))
        {
            return $this->data[$name];
        }
    }
}


You should check out the variable variables manual on the PHP site. With that, it could look like:

<?php
   echo ${'this->'.$yourvariable};  
?>


I prefer to use call_user_func and pass the parameters as array instead.

public function dynamicGetterExample()
{
    $property = 'name'; // as an example...
    $getter = 'get'.ucfirst($property);

    $value = call_user_func(array($this,$getter));
    if (empty($value)) {
        throw new \Exception('Required value is empty for property '.$property);
    }

    return $value;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜