PHP Custom Function Implementation assign of Array Allocation to Template and extract of Variable Allocation to Template Function Example

  • 2021-10-11 17:57:39
  • OfStack

This article describes the example of PHP custom function to achieve assign () array allocation to the template and extract () variable allocation to the template function. Share it for your reference, as follows:

Here, the tp framework template variable allocation and assignment operation is simulated.

extract($arr); //extract Function: From the array will be imported into the current symbol table, the key as a variable, value as a value!
compact(); //--Create an array with variable names and their values


class base{
  public $array;
  public $key;
  public $val;
  public function assign($key,$val){
    if(array($val)){
      $this->array["$key"] = $val;
    }else{
      $this->array["$key"] = compact($val);
    }
  }
  public function display($tpl){
    $this->assign($this->key,$this->val);
    extract($this->array);
    if(file_exists($tpl)){ // Load the file when the template exists. 
      include $tpl;
    }
  }
}
class indexcontroller extends base{
  public function index(){
    $arr = array('a'=>'aaaaaaa','b'=>array('a'=>'111111','b'=>'22222','c'=>'3333'),'c'=>'ccccccc','d'=>'dddddd','e'=>'eeeee');
    $str = ' I am a string ';
    $this->assign('arr',$arr);
    $this->assign('str',$str);
    $this->display('index.html');
  }
}
$base = new base;
$base->index();

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: