[英]$this->“variable value” OOP PHP
我想知道它是否可能,如果是的話,我怎么會這樣做:
$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];
}
}
}
我更喜歡使用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;
}
您應該在PHP站點上查看變量變量手冊。 有了它,它可能看起來像:
<?php
echo ${'this->'.$yourvariable};
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.