我想知道这是否可能,如果是的话,我应该如何实现:
$this->id
<——我有这样的东西。但为了使它更有用,我想有$this->(and here to change the values)
为例:我可能有$this->id $this->allID $this->proj_id
我怎样才能使我有$this->($myvariable here, that has a unique name in it)
呢?
您可以简单地使用:
$variable = 'id';
if ( isset ( $this->{$variable} ) )
{
echo $this->{$variable};
}
解决方案如下:http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
使用它的一个例子是:
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];
}
}
}
您应该查看PHP站点上的变量手册。这样,它看起来就像:
<?php
echo ${'this->'.$yourvariable};
?>
我更喜欢使用call_user_func
并将参数传递为array
。
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;
}