html elements class


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /* creates an html element, like in js */
  2. class html_element
  3. {
  4. /* vars */
  5. var $type;
  6. var $attributes;
  7. var $self_closers;
  8.  
  9. /* constructor */
  10. function html_element($type,$self_closers = array('input','img','hr','br','meta','link'))
  11. {
  12. $this->type = strtolower($type);
  13. $this->self_closers = $self_closers;
  14. }
  15.  
  16. /* get */
  17. function get($attribute)
  18. {
  19. return $this->attributes[$attribute];
  20. }
  21.  
  22. /* set -- array or key,value */
  23. function set($attribute,$value = '')
  24. {
  25. if(!is_array($attribute))
  26. {
  27. $this->attributes[$attribute] = $value;
  28. }
  29. else
  30. {
  31. $this->attributes = array_merge($this->attributes,$attribute);
  32. }
  33. }
  34.  
  35. /* remove an attribute */
  36. function remove($att)
  37. {
  38. if(isset($this->attributes[$att]))
  39. {
  40. unset($this->attributes[$att]);
  41. }
  42. }
  43.  
  44. /* clear */
  45. function clear()
  46. {
  47. $this->attributes = array();
  48. }
  49.  
  50. /* inject */
  51. function inject($object)
  52. {
  53. if(@get_class($object) == __class__)
  54. {
  55. $this->attributes['text'].= $object->build();
  56. }
  57. }
  58.  
  59. /* build */
  60. function build()
  61. {
  62. //start
  63. $build = '<'.$this->type;
  64.  
  65. //add attributes
  66. if(count($this->attributes))
  67. {
  68. foreach($this->attributes as $key=>$value)
  69. {
  70. if($key != 'text') { $build.= ' '.$key.'="'.$value.'"'; }
  71. }
  72. }
  73.  
  74. //closing
  75. if(!in_array($this->type,$this->self_closers))
  76. {
  77. $build.= '>'.$this->attributes['text'].'</'.$this->type.'>';
  78. }
  79. else
  80. {
  81. $build.= ' />';
  82. }
  83.  
  84. //return it
  85. return $build;
  86. }
  87.  
  88. /* spit it out */
  89. function output()
  90. {
  91. echo $this->build();
  92. }
  93. }

URL: http://davidwalsh.name/create-html-elements-php-htmlelement-class

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.