2015-09-15 49 views
1

我要聲明一個類中的變量與未知名PHP聲明公共變量內部功能

class Example { 
    function newVar($name, $value) { 
     $this->$name = $value; 
    } 
} 

而且我想用這種方式

$c = new Example(); 
$c->newVar('MyVariableName', "This is my Value"); 
echo($c->MyVariableName); 

重要的是,我不知道變量的名字。所以我不能把public $MyVariable放在課堂上。

無論如何可能嗎?如果是的話,我可以在不同的示波器上做這個(privateprotected,public)?

+0

的屬性自動公開,你不能定義另一知名度 – Rizier123

+0

不代碼工作?對我來說,它迴應'這是我的價值' –

+0

可能重複的[你可以在PHP中動態創建實例屬性?](http://stackoverflow.com/questions/829823/can-you-create-instance-properties-dynamically- in-php) – samrap

回答

1

ü應該使用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 

http://php.net/manual/en/language.oop5.magic.php

+0

不需要'newVar()'方法,'$ c-> MyVariableName =「New value」;'只需實例化和重新分配。 – samrap

+0

@samrap當然,我知道)。 – voodoo417

+0

我只是澄清OP。當前的例子看起來像你必須首先使用'newVar()'方法來實例化「屬性」 – samrap

0

您正在尋找神奇的召喚。在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"; 
    } 
} 

這也將爲私有,保護和公共工作。也可以使用它作爲需要在一個類

+0

'__call'魔術方法用於調用動態方法,而不是設置屬性。請看看http://php.net/manual/en/language.oop5.overloading.php – samrap

1

如果我理解這個正確,您可以通過鍵值陣列

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')); 

而不是使用私有你可以使用保護以及調整一點點的調用方法。

+0

這和OP已經有了一樣的,只是更多的代碼。 – Rizier123

+0

但作爲一個對象,它將永遠是公開的,但現在你可以對變量和函數有不同的權限類型 – Tom

+0

@ voodoo417我喜歡他的方法比我的更好。 – Tom