За последние 24 часа нас посетили 36749 программистов и 1810 роботов. Сейчас ищут 903 программиста ...

Есть класс построения элементов, как его реализуют echo out;

Тема в разделе "PHP для новичков", создана пользователем Conus, 25 фев 2017.

  1. Conus

    Conus Активный пользователь

    С нами с:
    21 окт 2015
    Сообщения:
    92
    Симпатии:
    0
    чё-то вспомнить не могу, ниже класс приведён
    писал, работало
    Код (Text):
    1. $html = new HtmlTag;
    2. $html->createElement('div');
    и т д
    потом

    echo $html; или как?


    Код (Text):
    1. class HtmlTag{
    2.  
    3.     private static $_instance = null;  
    4.     private $_top = null;
    5.     private $tag = null;
    6.     private $attributes = null;
    7.     private $class = null;
    8.     private $text = '';  
    9.     private $content = null;
    10.     private $autoclosed = true;
    11.     private $textFirst = false;
    12.  
    13.     private function _construct($tag, $top = null){ $this->tag = $tag; $this->_top =& $top; return $this; }
    14.  
    15.     public static function createElement($tag = ''){ self::$_instance = new HtmlTag($tag); return self::$_instance; }
    16.     public function addElement($tag)
    17.     {
    18.         $htmlTag = null;
    19.         if(is_null($this->content)){ $this->content = array(); $this->autoclosed = false; }
    20.         if(is_object($tag) && get_class($tag) == get_class($this))
    21.         {
    22.             $htmlTag = $tag;
    23.             $htmlTag->_top = $this->_top;
    24.             $this->content[] = $htmlTag;
    25.         }
    26.         else
    27.         {
    28.             $htmlTag = new HtmlTag($tag, (is_null($this->_top) ? $this : $this->_top ));
    29.             $this->content[] = $htmlTag;
    30.         }
    31.         return $htmlTag;
    32.     }
    33.  
    34.     public function setof($ar){
    35.      foreach($ar as $k=>$value)
    36.      {
    37.         if(is_null($this->attributes))
    38.         $this->attributes = array();
    39.         $this->attributes[$k] = $value;
    40.      }
    41.         return $this;
    42.     }
    43.  
    44.     public function setText($value){  $this->text = $value;return $this; }
    45.  
    46.     public function set($name,$value)
    47.     { if(is_null($this->attributes)) $this->attributes = array(); $this->attributes[$name] = $value; return $this; }
    48.     public function addClass($value){ if(is_null($this->class)) $this->class = array(); $this->class[] = $value; return $this;  }
    49.  
    50.     public function removeClass($class){
    51.         if(!is_null($this->class)){
    52.             unset($this->class[array_search($class, $this->class)]);
    53.             // foreach($this->class as $key=>$value){
    54.                 // if($class == $value)
    55.                     // $this->class[$key] = '';
    56.             // }
    57.         }
    58.         return $this;
    59.     }
    60.  
    61.     public function showTextBeforeContent($bool){$this->textFirst = $bool; }  
    62.     public function __toString(){ return (is_null($this->_top) ? $this->toString() : $this->_top->toString() ); }
    63.  
    64.     public function toString(){
    65.         $string = '';
    66.         if(!empty($this->tag)){
    67.             $string .=  '<' . $this->tag;
    68.             $string .= $this->attributesToString();
    69.             if($this->autoclosed && empty($this->text)) $string .= '/>' . CHR(13) . CHR(10) . CHR(9);
    70.             else $string .= '>' . ($this->textFirst ?  $this->text.$this->contentToString() : $this->contentToString().$this->text ). '</' . $this->tag . '>';
    71.         }
    72.         else{  $string .= $this->contentToString(); }      
    73.         return $string;
    74.     }
    75.  
    76.     private function attributesToString(){
    77.         $string = '';
    78.         if(!is_null($this->attributes)){
    79.             foreach($this->attributes as $key => $value){
    80.                 if(!empty($value))
    81.                     $string .= ' ' . $key . '="' . $value . '"';
    82.             }
    83.         }
    84.         if(!is_null($this->class) && count($this->class) > 0 ){
    85.             $string .= ' class="' . implode(' ',$this->class) . '"';
    86.         }
    87.         return $string;
    88.     }
    89.  
    90.     private function contentToString(){
    91.         $string = '';
    92.         if(!is_null($this->content)){
    93.             foreach($this->content as $c){
    94.                 $string .= CHR(13) . CHR(10) . CHR(9) . $c->toString();
    95.             }
    96.         }
    97.         return $string;
    98.     }
    99. }
     
  2. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.600
    Симпатии:
    1.764
    Сработает, если в классе toString() заменить на __toString() - так этот магический метод правильно называется
     
  3. Conus

    Conus Активный пользователь

    С нами с:
    21 окт 2015
    Сообщения:
    92
    Симпатии:
    0
    в функции класса?
    не работает
     
    #3 Conus, 25 фев 2017
    Последнее редактирование: 25 фев 2017
  4. denis01

    denis01 Суперстар
    Команда форума Модератор

    С нами с:
    9 дек 2014
    Сообщения:
    12.227
    Симпатии:
    1.714
    Адрес:
    Молдова, г.Кишинёв
    думаю он имел ввиду вызвать метод __toString() у экземпляра класса
     
  5. Conus

    Conus Активный пользователь

    С нами с:
    21 окт 2015
    Сообщения:
    92
    Симпатии:
    0
    __construct
    Call to private HtmlTag::__construct() from invalid contex
    --- Добавлено ---
    Вспомнил, работает
    public HtmlTag
     
  6. alexblack

    alexblack Старожил

    С нами с:
    20 янв 2016
    Сообщения:
    640
    Симпатии:
    381
    Я слегка заморочился,у тебя в 13 строке не правильно определен конструктор: _construct а нужно __construct.Вот тебе исправленный код;

    PHP:
    1. <?
    2. class HtmlTag{
    3.     private static $_instance = null;
    4.     private $_top = null;
    5.     private $tag = null;
    6.     private $attributes = null;
    7.     private $class = null;
    8.     private $text = '';
    9.     private $content = null;
    10.     private $autoclosed = true;
    11.     private $textFirst = false;
    12.     private function __construct($tag, $top = null){ $this->tag = $tag; $this->_top =& $top; return $this; }
    13.     public static function createElement($tag = ''){ self::$_instance = new HtmlTag($tag); return self::$_instance; }
    14.     public function addElement($tag)
    15.     {
    16.         $htmlTag = null;
    17.         if(is_null($this->content)){ $this->content = array(); $this->autoclosed = false; }
    18.         if(is_object($tag) && get_class($tag) == get_class($this))
    19.         {
    20.             $htmlTag = $tag;
    21.             $htmlTag->_top = $this->_top;
    22.             $this->content[] = $htmlTag;
    23.         }
    24.         else
    25.         {
    26.             $htmlTag = new HtmlTag($tag, (is_null($this->_top) ? $this : $this->_top ));
    27.             $this->content[] = $htmlTag;
    28.         }
    29.         return $htmlTag;
    30.     }
    31.     public function setof($ar){
    32.      foreach($ar as $k=>$value)
    33.      {
    34.         if(is_null($this->attributes))
    35.         $this->attributes = array();
    36.         $this->attributes[$k] = $value;
    37.      }
    38.         return $this;
    39.     }
    40.     public function setText($value){  $this->text = $value;return $this; }
    41.     public function set($name,$value)
    42.     { if(is_null($this->attributes)) $this->attributes = array(); $this->attributes[$name] = $value; return $this; }
    43.     public function addClass($value){ if(is_null($this->class)) $this->class = array(); $this->class[] = $value; return $this;  }
    44.     public function removeClass($class){
    45.         if(!is_null($this->class)){
    46.             unset($this->class[array_search($class, $this->class)]);
    47.             // foreach($this->class as $key=>$value){
    48.                 // if($class == $value)
    49.                     // $this->class[$key] = '';
    50.             // }
    51.         }
    52.         return $this;
    53.     }
    54.     public function showTextBeforeContent($bool){$this->textFirst = $bool; }
    55.     public function __toString(){ return (is_null($this->_top) ? $this->toString() : $this->_top->toString() ); }
    56.     public function toString(){
    57.         $string = '';
    58.         if(!empty($this->tag)){
    59.             $string .=  '<' . $this->tag;
    60.             $string .= $this->attributesToString();
    61.             if($this->autoclosed && empty($this->text)) $string .= '/>' . CHR(13) . CHR(10) . CHR(9);
    62.             else $string .= '>' . ($this->textFirst ?  $this->text.$this->contentToString() : $this->contentToString().$this->text ). '</' . $this->tag . '>';
    63.         }
    64.         else{  $string .= $this->contentToString(); }    
    65.         return $string;
    66.     }
    67.     private function attributesToString(){
    68.         $string = '';
    69.         if(!is_null($this->attributes)){
    70.             foreach($this->attributes as $key => $value){
    71.                 if(!empty($value))
    72.                     $string .= ' ' . $key . '="' . $value . '"';
    73.             }
    74.         }
    75.         if(!is_null($this->class) && count($this->class) > 0 ){
    76.             $string .= ' class="' . implode(' ',$this->class) . '"';
    77.         }
    78.         return $string;
    79.     }
    80.     private function contentToString(){
    81.         $string = '';
    82.         if(!is_null($this->content)){
    83.             foreach($this->content as $c){
    84.                 $string .= CHR(13) . CHR(10) . CHR(9) . $c->toString();
    85.             }
    86.         }
    87.         return $string;
    88.     }
    89. }
    90. $el = HtmlTag::createElement('div');
    91. $el->setText('Hello');
    92. echo $el->toString();
    Который выведет:
    Код (Text):
    1. <div>Hello</div>
    Можешь попробовать.
    Теперь,когда поправили конструктор,можно выводить как я показал через метод,а можно просто:
    PHP:
    1. echo $el;
     
    #6 alexblack, 25 фев 2017
    Последнее редактирование: 25 фев 2017