[英]php declare public variable inside function
我想在一個名稱未知的類中聲明一個變量
class Example {
function newVar($name, $value) {
$this->$name = $value;
}
}
我想那樣使用
$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->MyVariableName);
重要的是,我不知道變量的名稱。 因此,我不能在課程中添加public $MyVariable
。
無論如何有可能嗎? 如果是,我可以在不同范圍( private
, protected
, public
)中執行此操作嗎?
如果我正確理解了這一點,則可以使用鍵值數組進行一些調整
class Example {
private $temp;
function __construct(){
$this->temp = array();
}
function newVar($name, $value) {
$this->temp[$name] = $value;
}
function getVar($name){
return $this->temp[$name];
}
}
$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->getVar('MyVariableName'));
除了使用私有以外,還可以使用受保護的。
U應該使用magic methods
__get
和__set
(示例,未經檢查):
class Example {
private $data = [];
function newVar($name, $value) {
$this->data[$name] = $value;
}
public function __get($property) {
return $this->data[$property];
}
public function __set($property, $value) {
$this->data[$property] = $value;
}
}
$c = new Example();
$c->newVar('MyVariableName', "This is my Value");
echo($c->MyVariableName);
// This is my Value
$c->MyVariableName = "New value";
echo($c->MyVariableName);
// New value
您正在尋找魔術的呼喚。 在PHP中,您可以使用__call()
函數執行類似的操作。 在這里看看: http : //www.garfieldtech.com/blog/magical-php-call
在我的頭頂上,像
function __call($vari, $args){
if(isset($this->$vari){
$return = $this->$vari;
}else{
$return = "Nothing set with that name";
}
}
這也將適用於私人,受保護的和公共的。 也可以根據需要使用它來調用類中的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.