How do I add a new member variable in PHP?

2019-08-12 20:45发布

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

How do I implement this?

标签: php smarty
6条回答
Rolldiameter
2楼-- · 2019-08-12 20:57

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');
查看更多
闹够了就滚
3楼-- · 2019-08-12 20:59
class Name {
   private $values = array()

   function assign($name,$value) {
       $this->values[$name] = $value;
   }
}
查看更多
Ridiculous、
4楼-- · 2019-08-12 21:00
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.

查看更多
迷人小祖宗
5楼-- · 2019-08-12 21:16

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

查看更多
爷、活的狠高调
6楼-- · 2019-08-12 21:16
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;
查看更多
兄弟一词,经得起流年.
7楼-- · 2019-08-12 21:19

I would say

class Name{
    private $_values = array(); // or protected if you prefer
    function assign($name,$value){
       $this->_values[$name] = $value;
    }
}
查看更多
登录 后发表回答