2009-11-19 40 views
1

我想要做的事,如:如何在PHP中添加新的成員變量?

class Name{ 
    function assign($name,$value){ 
    } 
} 

這是幾乎一樣assign在智者:

$smarty->assign('name',$value); 
$smarty->display("index.html"); 

如何實現這一點?

回答

4
class Name { 
    private $values = array() 

    function assign($name,$value) { 
     $this->values[$name] = $value; 
    } 
} 
0

我想說

class Name{ 
    private $_values = array(); // or protected if you prefer 
    function assign($name,$value){ 
     $this->_values[$name] = $value; 
    } 
} 
+0

這樣只有一個變量可以分配。 – Mask 2009-11-19 05:31:12

+0

你想分配一個數組? – RageZ 2009-11-19 05:31:50

1

問題有點模糊。如果你想保持$名稱$值圍繞以備將來使用,你可以這樣做:

class Name { 

    protected $_data= array(); 

    function assign($name,$value) { 
     $this->_data[$name]= $value; 
    } 
} 

然後使在包含的模板文件中可用的變量:

class Templater { 

    protected $_data= array(); 

    function assign($name,$value) { 
     $this->_data[$name]= $value; 
    } 

    function render($template_file) { 
     extract($this->_data); 
     include($template_file); 
    } 
} 

$template= new Templater(); 
$template->assign('myvariable', 'My Value'); 
$template->render('path/to/file.tpl'); 

如果路徑/to/file.tpl包含:

<html> 
<body> 
This is my variable: <b><?php echo $myvariable; ?></b> 
</body> 
</html> 

你會得到輸出這樣

這是我的變量:我的價值

1
class Name{ 
    private $_vars; 
    function __construct() { 
     $this->_vars = array(); 
    } 

    function assign($name,$value) { 
     $this->_vars[$name] = $value; 
    } 

    function display($templatefile) { 
     extract($this->_vars); 
     include($templatefile); 
    } 
} 

extract()呼叫從一個陣列到存在作爲命名爲與對應於所述陣列的值值中的每個關鍵變量暫時拉鍵 - 值對。從文件

class registry 
{ 
    private $data = array(); 

    static function set($name, $value) 
    { 
      $this->data[$name] = $value; 
    } 

    static function get($value) 
    { 
      return isset($this->data[$name]) ? $this->data[$name] : false; 
    } 

} 

,並獲得這樣的:

+0

難道你不是指'$ this - > _ vars'? – deceze 2009-11-19 05:40:40

+0

您認爲這是MVC嗎?我可以看到它將View和Logic分開,但我不知道Modal和Control.Do? – Mask 2009-11-19 05:50:27

+0

通常情況下,你會得到*要傳遞給'assign()'的數據將來自模型。由於這裏沒有使用實際的數據,因此您只會看到視圖和控制器的元素。 – Amber 2009-11-19 06:23:37

0

您應該創建一個全球註冊類,從而使您的變量到你的HTML文件

registry::get('my already set value'); 
0
 
class XY 
{ 

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

public function __get($value) 
{ 
     return isset($this->$name) ? $this->$name : false; 
} 

} 

$xy = new XY(); 

$xy->username = 'Anton'; 
$xy->email = 'anton{at}blabla.com'; 


echo "Your username is: ". $xy->username; 
echo "Your Email is: ". $xy->email;