How do I add a new member variable in PHP?
I want to do something like:
class Name{
function assign($name,$value){
}
}
Which is pretty much the same as assign
in smarty:
$smarty->assign('name',$value);
$smarty->display("index.html开发者_JS百科");
How do I implement this?
class Name {
private $values = array()
function assign($name,$value) {
$this->values[$name] = $value;
}
}
The question's a little vague. If you want to keep the $value of $name around for future use you could do something like:
class Name {
protected $_data= array();
function assign($name,$value) {
$this->_data[$name]= $value;
}
}
Then to make the variables available in an included template file:
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');
And if path/to/file.tpl contains:
<html>
<body>
This is my variable: <b><?php echo $myvariable; ?></b>
</body>
</html>
You would get output like this
This is my variable: My Value
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);
}
}
The extract()
call temporarily pulls key-value pairs from an array into existence as variables named for each key with values corresponding to the array values.
I would say
class Name{
private $_values = array(); // or protected if you prefer
function assign($name,$value){
$this->_values[$name] = $value;
}
}
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;
You should create a global registry class to make your variables available to your HTML file:
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;
}
}
And access like this from your files:
registry::get('my already set value');
精彩评论