За последние 24 часа нас посетили 185359 программистов и 1973 робота. Сейчас ищут 1150 программистов ...

Как получить данные переменной из функции?

Тема в разделе "PHP для новичков", создана пользователем romagromov, 13 апр 2016.

  1. romagromov

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

    С нами с:
    17 дек 2015
    Сообщения:
    73
    Симпатии:
    0
    Здравствуйте!
    Очень поверхностно знаком с функциями.

    Есть такой код для вывода комментариев.

    PHP:
    1. <?php
    2. /**
    3. * JComments - Joomla Comment System
    4. *
    5. * @version 3.0
    6. * @package JComments
    7. * @author Sergey M. Litvinov (smart@joomlatune.ru)
    8. * @copyright (C) 2006-2013 by Sergey M. Litvinov (http://www.joomlatune.ru)
    9. * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
    10. */
    11.  
    12. defined('_JEXEC') or die;
    13.  
    14. /**
    15. * Threaded comments list template
    16. *
    17. */
    18. class jtt_tpl_tree extends JoomlaTuneTemplate
    19. {
    20.     function render()
    21.     {
    22.         $comments = $this->getVar('comments-items');
    23.  
    24.         if (isset($comments)) {
    25.             $this->getHeader();
    26. ?>
    27. <div class="comments-list" id="comments-list-0">
    28. <?php
    29.             $i = 0;
    30.             $count = count($comments);
    31.             $currentLevel = 0;
    32.        
    33.             foreach($comments as $id => $comment) {
    34.                 if ($currentLevel < $comment->level) {
    35. ?>
    36.     </div>
    37.     <div class="comments-list" id="comments-list-<?php echo $comment->parent; ?>">
    38. <?php              
    39.                 } else {
    40.                     $j = 0;
    41.    
    42.                     if ($currentLevel >= $comment->level) {
    43.                         $j = $currentLevel - $comment->level;
    44.                     } else if ($comment->level > 0 && $i == $count - 1) {
    45.                         $j = $comment->level;
    46.                     }
    47.  
    48.                     while($j > 0) {
    49. ?>
    50.     </div>
    51. <?php
    52.                         $j--;
    53.                     }
    54.                 }
    55. ?>
    56.         <div class="<?php echo ($i%2 ? 'odd' : 'even'); ?>" id="comment-item-<?php echo $id; ?>">
    57. <?php
    58.                 echo $comment->html;
    59.  
    60.                 if ($comment->children == 0) {
    61. ?>
    62.         </div>
    63. <?php
    64.                 }
    65.                
    66.                 if ($comment->level > 0 && $i == $count - 1) {
    67.                     $j = $comment->level;
    68.                 }
    69.  
    70.                 while($j > 0) {
    71. ?>
    72.     </div>
    73. <?php                   $j--;
    74.                 }
    75.  
    76.                 $i++;
    77.                 $currentLevel = $comment->level;
    78.             }
    79. ?>
    80. </div>
    81. <div id="comments-list-footer"><?php echo $this->getFooter();?></div>
    82. <?php
    83.         } else {
    84.             // display single comment item (works when new comment is added)
    85.             $comment = $this->getVar('comment-item');
    86.  
    87.             if (isset($comment)) {
    88.                 $i = $this->getVar('comment-modulo');
    89.                 $id = $this->getVar('comment-id');
    90. ?>
    91.     <div class="<?php echo ($i%2 ? 'odd' : 'even'); ?>" id="comment-item-<?php echo $id; ?>"><?php echo $comment; ?></div>
    92. <?php
    93.             } else {
    94. ?>
    95. <div class="comments-list" id="comments-list-0"></div>
    96. <?php
    97.             }
    98.         }
    99.  
    100.     }
    101.  
    102.     /*
    103.     *
    104.     * Display comments header and small buttons: rss and refresh
    105.     *
    106.     */
    107.     function getHeader()
    108.     {
    109.         $object_id = $this->getVar('comment-object_id');
    110.         $object_group = $this->getVar('comment-object_group');
    111.  
    112.         $btnRSS = '';
    113.         $btnRefresh = '';
    114.        
    115.         if ($this->getVar('comments-refresh', 1) == 1) {
    116.             $btnRefresh = '<a class="refresh" href="#" title="'.JText::_('BUTTON_REFRESH').'" onclick="jcomments.showPage('.$object_id.',\''. $object_group . '\',0);return false;">&nbsp;</a>';
    117.         }
    118.  
    119.         if ($this->getVar('comments-rss') == 1) {
    120.             $link = $this->getVar('rssurl');
    121.             if (!empty($link)) {
    122.                 $btnRSS = '<a class="rss" href="'.$link.'" title="'.JText::_('BUTTON_RSS').'" target="_blank">&nbsp;</a>';
    123.             }
    124.         }
    125. ?>
    126.  
    127.        
    128.        
    129.  
    130. <h4 id="comments"><?php echo JText::_('COMMENTS_LIST_HEADER');?> <?php echo $btnRSS; ?><?php echo $btnRefresh; ?></h4>
    131. <?php
    132.     }
    133.  
    134.     /*
    135.     *
    136.     * Display RSS feed and/or Refresh buttons after comments list
    137.     *
    138.     */
    139.     function getFooter()
    140.     {
    141.         $footer = '';
    142.  
    143.         $object_id = $this->getVar('comment-object_id');
    144.         $object_group = $this->getVar('comment-object_group');
    145.  
    146.         $lines = array();
    147.  
    148.         if ($this->getVar('comments-refresh', 1) == 1) {
    149.             $lines[] = '<a class="refresh" href="#" title="'.JText::_('BUTTON_REFRESH').'" onclick="jcomments.showPage('.$object_id.',\''. $object_group . '\',0);return false;">'.JText::_('BUTTON_REFRESH').'</a>';
    150.         }
    151.  
    152.         if ($this->getVar('comments-rss', 1) == 1) {
    153.             $link = $this->getVar('rssurl');
    154.             if (!empty($link)) {
    155.                 $lines[] = '<a class="rss" href="'.$link.'" title="'.JText::_('BUTTON_RSS').'" target="_blank">'.JText::_('BUTTON_RSS').'</a>';
    156.             }
    157.         }
    158.  
    159.         if ($this->getVar('comments-can-subscribe', 0) == 1) {
    160.             $isSubscribed = $this->getVar('comments-user-subscribed', 0);
    161.  
    162.             $text = $isSubscribed ? JText::_('BUTTON_UNSUBSCRIBE') : JText::_('BUTTON_SUBSCRIBE');
    163.             $func = $isSubscribed ? 'unsubscribe' : 'subscribe';
    164.  
    165.             $lines[] = '<a id="comments-subscription" class="subscribe" href="#" title="' . $text . '" onclick="jcomments.' . $func . '('.$object_id.',\''. $object_group . '\');return false;">'. $text .'</a>';
    166.         }
    167.  
    168.         if (count($lines)) {
    169.             $footer = implode('<br />', $lines);
    170.         }
    171.  
    172.         return $footer;
    173.     }
    174. }
    В функции render есть переменная $count.

    Если добавить вывод содержимого переменного прямо в функции

    (фргамент кода)


    PHP:
    1. <?php
    2.             $i = 0;
    3.            
    4.             $count = count($comments);
    5.             $currentLevel = 0;
    6.             echo $count;
    7.        
    8.             foreach($comments as $id => $comment) {
    9.                 if ($currentLevel < $comment->level) {
    10. ?>
    То значение выводится, но не в том месте, где это нужно.

    Нужно, что бы оно выводилось в заголовке h4

    HTML:
    1. <h4 id="comments"><?php echo JText::_('COMMENTS_LIST_HEADER').' '.$count;?> <?php echo $btnRSS; ?><?php echo $btnRefresh; ?></h4>
    Но ничего выводится.

    Объясните пожалуйста, как передать туда значение переменной.
    Спасибо.
     
  2. denis01

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

    С нами с:
    9 дек 2014
    Сообщения:
    12.227
    Симпатии:
    1.714
    Адрес:
    Молдова, г.Кишинёв
  3. romagromov

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

    С нами с:
    17 дек 2015
    Сообщения:
    73
    Симпатии:
    0
    Судя по второму мануалу, нужно использовать global

    так и делаю

    PHP:
    1. class jtt_tpl_tree extends JoomlaTuneTemplate
    2. {
    3.     function render()
    4.     {
    5.         global $count, $comments;
    6.         $comments = $this->getVar('comments-items');
    7.  
    8.         if (isset($comments)) {
    9.             $this->getHeader();
    10. ?>
    11. <div class="comments-list" id="comments-list-0">
    12. <?php
    13.             $i = 0;
    14.            
    15.             $count = count($comments);
    16.             $currentLevel = 0;
    17.        
    18.             foreach($comments as $id => $comment) {
    19.                 if ($currentLevel < $comment->level) {
    20. ?>
    Не выводит...
     
  4. smitt

    smitt Старожил

    С нами с:
    3 янв 2012
    Сообщения:
    3.166
    Симпатии:
    65
    не нужно
     
  5. romagromov

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

    С нами с:
    17 дек 2015
    Сообщения:
    73
    Симпатии:
    0
    А что нужно-то?
     
  6. smitt

    smitt Старожил

    С нами с:
    3 янв 2012
    Сообщения:
    3.166
    Симпатии:
    65
    Голову включать и гуглить
    http://forum.joomla.org/viewtopic.php?p=2460747
    --- Добавлено ---
    Догадаешься или просто скопируешь все?
    --- Добавлено ---
    Задачу опиши, может не правильно досказал)
    Тебе количество комментариев нужно вывести в h4?
     
  7. romagromov

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

    С нами с:
    17 дек 2015
    Сообщения:
    73
    Симпатии:
    0
    Я видел этот вариант

    Дело в ом, что я вывожу не в стороннем компоненте, а самом шаблоне Jcomments.
    Я не понимаю, как там получить
    PHP:
    1. $count = JComments::getCommentsCount($this->article->id, 'com_content');
    В моем случае из компонента easyblog

    пробую так

    PHP:
    1. <?php $commentsAPI = JPATH_SITE . '/components/com_jcomments/jcomments.php';
    2. if (file_exists($commentsAPI)) {
    3. require_once($commentsAPI);
    4. $count = JComments::getCommentsCount($this->post->id, 'com_easyblog');
    5. echo '('. $count . ')';
    6. }
    Выводит общее количество комментариев, а не из текущего материала.

    И потом, мне казалось, что в самом шаблоне можно получить количество просто из переменной.
    --- Добавлено ---
    Ок, получилось так.

    PHP:
    1. <?php $commentsAPI = JPATH_SITE . '/components/com_jcomments/jcomments.php';
    2.     $object_id = $this->getVar('comment-object_id');
    3. if (file_exists($commentsAPI)) {
    4. require_once($commentsAPI);
    5. $count = JComments::getCommentsCount($object_id, 'com_easyblog');
    6. echo '('. $count . ')';
    7. }
    8.  
    9. ?>

    Но мне казалось, это очень громоздко. Если в этом же файле можно просто переменную получить...
     
  8. smitt

    smitt Старожил

    С нами с:
    3 янв 2012
    Сообщения:
    3.166
    Симпатии:
    65
    Ну ибать...
    либо в $this->getHeader(); передай значение $comments
    либо в getHeader() вызови count($this->getVar('comments-items'))

    И ради этого ты потратил целое утро...
     
  9. romagromov

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

    С нами с:
    17 дек 2015
    Сообщения:
    73
    Симпатии:
    0
    в getHeader() вызвал count($this->getVar('comments-items'))
    Я же сразу написал - нубер.
    Работает и красиво.
    Спасибо!