Модераторы: skyboy, MoLeX, Aliance, ksnk
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Разобраться смассивом 
V
    Опции темы
Predator199
  Дата 8.6.2014, 21:00 (ссылка)    | (голосов:2) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 412
Регистрация: 1.2.2012

Репутация: -3
Всего: -4



Скажите как достать содержимое объекта...

Скрипт 1
Код

//---------------------------------------------------------
// Auto-posting of topics
//---------------------------------------------------------
$classToLoad        = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . '/sources/classes/post/classPost.php', 'classPost', 'forums' );
$classToLoad            = IPSLib::loadLibrary( IPSLib::getAppDir('downloads') . '/sources/classes/topics.php', 'topicsLibrary', 'downloads' );
$lib_topics        = new $classToLoad( $this->registry );
$file['file_submitter_name'] = $author_name;
$file['record_storagetype'] = $this->settings['idm_filestorage'];
$lib_topics     -> sortTopic( array_merge( $file, $save_array ), $category, $type );

print_r($lib_topics);


Скрипт 2, находится функция  sortTopic(. Содержимое...

Код

    public function sortTopic( $file, $category, $type = 'new', $mid_override = 0 )
    {
        //---------------------------------------------------------
        // Some init
        //---------------------------------------------------------
        
        $this->base_url    = $this->settings['board_url'] . '/index.php?';
        $this->cfields    = '';
        
        $this->registry->class_localization->loadLanguageFile( array( 'public_global' ), 'core' );
    
        //---------------------------------------------------------
        // Is file open?
        //---------------------------------------------------------

        if( !$file['file_open'] )
            return false;
        
        
        //---------------------------------------------------------
        // Custom fields added to topic?
        //---------------------------------------------------------

        if( $category['ccfields'] )
        {
            $classToLoad        = IPSLib::loadLibrary( IPSLib::getAppDir('downloads') . '/sources/classes/cfields.php', 'customFields', 'downloads' );
         $fields                = new $classToLoad( $this->registry );
         $fields->file_id    = $file['file_id'];
         $fields->cat_id        = $category['ccfields'];
         $fields->cache_data    = $this->cache->getCache('idm_cfields');
     
         $fields->init_data( 'view' );
         $fields->parseToView();
         
         foreach( $fields->out_fields as $id => $data )
         {
             if( $fields->cache_data[ $id ]['cf_topic'] )
             {
                 $data = $data ? $data : $this->lang->words['cat_no_info'];
                 
                    $this->cfields .= '' . $fields->field_names[ $id ] . ': ' . $data . "<br />";
                }
         }
        }
    
        //---------------------------------------------------------
        // Should topic be posted at all?
        //---------------------------------------------------------

        if( $category['coptions']['opt_topice'] == 1 )
        {
            if( $category['coptions']['opt_topicf'] )
            {
                //---------------------------------------------------------
                // Get some libraries we need
                //---------------------------------------------------------

                ipsRegistry::getAppClass( 'forums' );

                $classToLoad            = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . '/sources/classes/post/classPost.php', 'classPost', 'forums' );
                $classToLoad            = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . '/sources/classes/post/classPostForms.php', 'classPostForms', 'forums' );
                $this->post                = new $classToLoad( $this->registry );

                //---------------------------------------------------------
                // Format prefix/suffix
                //---------------------------------------------------------
        
                $category['coptions']['opt_topics'] = str_replace( "{catname}", $category['cname'], $category['coptions']['opt_topics'] );
                $category['coptions']['opt_topicp'] = str_replace( "{catname}", $category['cname'], $category['coptions']['opt_topicp'] );
                
                //---------------------------------------------------------
                // Verify topic "poster"
                //---------------------------------------------------------

                if( !$mid_override )
                    $file['file_submitter'] = ( $type == 'new' ) ? $this->memberData['member_id'] : $file['file_submitter'];
                
                
                if( $file['file_submitter'] == 0 AND !$file['file_submitter_name'] )
                    $file['file_submitter_name'] = $this->lang->words['global_guestname'];
            

                $member            = $file['file_submitter'] ? IPSMember::load( $file['file_submitter'] ) : IPSMember::setUpGuest();

                if( !$member['member_id'] )
                    $this->request['UserName']    = $file['file_submitter_name'];
                    

                //-----------------------------------------
                // Retrieve tags, in case this is not a form submit
                //-----------------------------------------

                if( !$_POST['ipsTags'] )
                {
                    $this->DB->build( array( 'select' => '*', 'from' => 'core_tags', 'where' => "tag_meta_app='downloads' AND tag_meta_area='files' AND tag_meta_id=" . $file['file_id'] ) );
                    $this->DB->execute();
                    
                    while( $r = $this->DB->fetch() )
                    {
                        $_POST['ipsTags'][]    = $r['tag_text'];

                        if( $r['tag_prefix'] )
                            $_REQUEST['ipsTags_prefix']    = 1;
                    }
                }

                $_backupMember        = $this->memberData;
                $this->memberData    = $member;
    
                //---------------------------------------------------------
                // Update topic or post a new one?
                //---------------------------------------------------------
                    
                if(    $type == 'new' )
                    $this->_postNewTopic( $file, $category, $member );
                else
                    $this->_postUpdatedTopic( $file, $category, $member );

                $this->memberData    = $_backupMember;
            
                return true;
            }
        }
        
        return false;
    }


Итог  данной функции, получаем огромный массив. Из которого нужно заполучить содержимое _topicData
Код

rs_member] => 0 ) [_topicData:protected] => Array ( [title] => 123123 - ww [title_seo] => 123123-ww [state] => open [posts] => 0 [starter_id] => 1 
[start_date] => 1402336600 [last_poster_id] => 1 [last_post] => 1402336600 [author_mode] => 1 [poll_state] => 0 [last_vote] => 0 [views] => 0 
[forum_id] => 66 [approved] => 1 [topic_archive_status] => 0 [pinned] => 0 [topic_open_time] => 0 [topic_close_time] => 0 [file_id] => 244 
[tid] => 324 ) [_postData:protected] => Arra

Массив есть в переменной $lib_topics. Но если прописать так $lib_topics->_topicData, не получается выхватить. То ли видимости нет, скажите как исправить...  Как заставить вытащить  _topicData

Итог получаем когда делаем обращение к $this->_postNewTopic( $file, $category, $member );
Содержимое _postNewTopic

Код

protected function _postNewTopic( $file, $category, $member )
    {                    
        $pred_title = IPSText::UNhtmlspecialchars( $file['file_name'].' - '.$file['short']);
        $topic_title_max_len = $this->settings['topic_title_max_len'];
         
        if(strlen($pred_title) > $topic_title_max_len)
            $pred_title =  substr($pred_title, 0, $topic_title_max_len).'...';
         
        $ttitle            = IPSText::truncate( $pred_title , $topic_title_max_len - intval(strlen($category['coptions']['opt_topicp'])) - intval(strlen($category['coptions']['opt_topics'])) );

        if( $category['coptions']['opt_topicp'] )
            $ttitle        = $category['coptions']['opt_topicp'] . $ttitle;
        if( $category['coptions']['opt_topics'] )
            $ttitle        .= $category['coptions']['opt_topics'];                
        
        $post_content    = $this->_buildPostContent( $file, $category );
        
        try
        {
            $this->post->setBypassPermissionCheck( true );
            $this->post->setIsAjax( false );
            $this->post->setPublished( true );
            $this->post->setForumID( $category['coptions']['opt_topicf'] );
            $this->post->setAuthor( $member );
            $this->post->setPostContentPreFormatted( $post_content );
            $this->post->setTopicTitle( $ttitle );
            $this->post->file_id($file['file_id']);
            $this->post->setSettings( array( 'enableSignature' => 1,
                                       'enableEmoticons' => 1,
                                       'post_htmlstatus' => 0 ) );
            
            if( $this->post->addTopic() === false )
            {
                if( $this->debugMode )
                    print_r($this->post->getPostError());exit;

                return false;
            }
            
            $topic = $this->post->getTopicData();
            
            $this->DB->update( "downloads_files", array( 'file_topicid' => $topic['tid'], 'file_topicseoname' => $topic['title_seo'] ), "file_id=" . $file['file_id'] );
                
        }
        catch( Exception $e )
        {
            if( $this->debugMode )
                print $e->getMessage();exit;


            return false;
        }
        
        return true;
    }




Прописывал Public, не выходит. Что не так?

Это сообщение отредактировал(а) Aliance - 11.6.2014, 10:14
PM MAIL   Вверх
Predator199
Дата 10.6.2014, 20:39 (ссылка)    | (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 412
Регистрация: 1.2.2012

Репутация: -3
Всего: -4



Хелп smile 
PM MAIL   Вверх
Aliance
Дата 11.6.2014, 10:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


I ♥ <script>
****


Профиль
Группа: Модератор
Сообщений: 6418
Регистрация: 2.8.2004
Где: spb

Репутация: 14
Всего: 137



Написать метод в классе, который вернет закрытые данные. Но лучше написать свой класс, унаследовать его от родителя и реализовать там только этот метод. И везде обращаться к своему классу, чтобы не трогать исходники.
PM MAIL WWW ICQ Skype   Вверх
Predator199
Дата 11.6.2014, 13:52 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 412
Регистрация: 1.2.2012

Репутация: -3
Всего: -4



Цитата(Aliance @ 11.6.2014,  10:15)
Написать метод в классе, который вернет закрытые данные. Но лучше написать свой класс, унаследовать его от родителя и реализовать там только этот метод. И везде обращаться к своему классу, чтобы не трогать исходники.

Спс.  Я не совсем понимаю...

Вот я перенес два класса в 1 скрипт
Код

class topicsLibrary {

    protected $post;
    protected $topic        = array();
    protected $registry;
    protected $DB;


    public function __construct( ipsRegistry $registry )
    {
        /* Make object */
        $this->registry = $registry;
        $this->DB       = $this->registry->DB();
    }
    

    public function sortTopic( $file, $category, $type = 'new', $mid_override = 0 )
    {

        ipsRegistry::getAppClass( 'forums' );

        $classToLoad            = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . '/sources/classes/post/classPost.php', 'classPost', 'forums' );
        $this->post                = new $classToLoad( $this->registry );
        
        $this->post->setBypassPermissionCheck( true );
        $this->post->setIsAjax( false );
        $this->post->setPublished( true );
        $this->post->setForumID( $category['coptions']['opt_topicf'] );
        $this->post->setAuthor( $member );
        $this->post->setPostContentPreFormatted( "111");
        $this->post->setTopicTitle('99');
        $this->post->file_id($file['file_id']);
        $this->post->setSettings( array( 'enableSignature' => 1,
                                       'enableEmoticons' => 1,
                                       'post_htmlstatus' => 0 ) );
             
        if( $this->post->addTopic() === false )
            return false;
        
 
        $topic = $this->post->getTopicData();
            
        $this->DB->update( "downloads_files", array( 'file_topicid' => $topic['tid'], 'file_topicseoname' => $topic['title_seo'] ), "file_id=" . $file['file_id'] );
            
        return true;
    }
    
}


//---------------------------------------------------


class public_downloads_post_submit extends ipsCommand
{

    protected $output            = "";
    protected $sortTopic        = "";
    protected $error_message    = '';
    protected $_like;
    protected $paid_file_message    = '';
    protected $postt;
    
    public function doExecute( ipsRegistry $registry )
    {

        require_once( IPS_ROOT_PATH . 'sources/classes/tags/bootstrap.php' );/*noLibHook*/
        $this->registry->setClass( 'downloadsTags', classes_tags_bootstrap::run( 'downloads', 'files' ) );
        
        $this->_mainSave( 'new' );
        
        $this->registry->output->addContent( $this->output );
        $this->registry->output->sendOutput();
    }
    
    
    protected function _mainSave( $type='new' )
    {
    
        
        $catid            = intval($this->request['file_cat']);
        
        $category = $this->registry->getClass('categories')->cat_lookup[ $catid ];
        require_once( IPSLib::getAppDir( 'downloads' ) . '/sources/storage/interface_storage.php' );/*noLibHook*/
    
        $save_array = array( 'file_name'        => $file['file_name'],
                             'short'            => IPSText::stripslashes( $_POST['short'] ),
                             'file_name_furl'    => $file['file_name_furl'],
                             'file_desc'        => $file['file_desc'],
                             'file_cat'            => $catid,
                             'file_open'        => $open,
                             'file_ipaddress'    => $this->member->ip_address,
                             'file_updated'        => time(),
                             'file_new'            => $file_new,
                             'file_post_key'    => $file['post_key'],
                             'file_cost'        => $file['file_cost'],
                             'file_nexus'        => $file['file_nexus'],
                             'file_version'        => IPSText::mbsubstr( $this->request['file_version'], 0, 24 ),
                             'file_changelog'    => trim( IPSText::br2nl( $this->request['file_changelog'] ) ),
                            );
        
        
        $where        = array( 'meta_parent_id'    => $save_array['file_cat'],
                              'member_id'        => $this->memberData['member_id'],
                              'existing_tags'    => explode( ',', IPSText::cleanPermString( $_POST['ipsTags'] ) ) );
                              
        
            
        /* Data Hook Location */
        IPSLib::doDataHooks( $save_array, 'downloadAddFile' );
            
        $this->DB->insert( "downloads_files", $save_array );    
        $file['file_id'] = $this->DB->getInsertId();
        $author_name = $this->memberData['members_display_name'];
        
        $this->registry->downloadsTags->add( $_POST['ipsTags'], array( 'meta_id'            => $file['file_id'],
                                                                           'meta_parent_id'    => $save_array['file_cat'],
                                                                           'member_id'            => $this->memberData['member_id'],
                                                                           'meta_visible'        => $save_array['file_open'] ) );
        

        //---------------------------------------------------------
        // Auto-posting of topics
        //---------------------------------------------------------
        $classToLoad            = IPSLib::loadLibrary( IPSLib::getAppDir( 'forums' ) . '/sources/classes/post/classPost.php', 'classPost', 'forums' );
        $classToLoad    = IPSLib::loadLibrary( IPSLib::getAppDir('downloads') . '/sources/classes/topics.php', 'topicsLibrary', 'downloads' );
        $this -> postt = new $classToLoad( $this->registry );
        
        $file['file_submitter_name'] = $author_name;
        $file['record_storagetype'] = $this->settings['idm_filestorage'];

        $this -> postt -> sortTopic( array_merge( $file, $save_array ), $category, $type );
        
        print_r($this->postt);
        
    }
}



Во втором классе public_downloads_post_submit. В самом низу, попытался , что та сделать. 
Код

print_r($this->postt);


$this все, что содержит $this доступно. Попытался в не е как то перенести. Все равно,что та не получается. Вроде бы и перенес, но не доступно. Класс topicsLibrary, недоступен по прежнему. smile 

Класс topicsLibrary теперь находится в классе public_downloads_post_submit Object

Код

> [_like:protected] => [paid_file_message:protected] => [postt:protected] => topicsLibrary Object ( [post:protected] => classPost Object ( [class_attach] => [mode


Так $this->postt я его достаю но , что внутри этого класса. По прежднему недоступно...
PM MAIL   Вверх
Aliance
Дата 11.6.2014, 14:20 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


I ♥ <script>
****


Профиль
Группа: Модератор
Сообщений: 6418
Регистрация: 2.8.2004
Где: spb

Репутация: 14
Всего: 137



То, что ты пишешь, понять очень сложно! Пока ты не научишься писать грамотно, пользоваться спеллчекером и кнопкой "предварительный просмотр", тебе не смогут помочь, потому что понять, что ты написал - довольно сложно!
PM MAIL WWW ICQ Skype   Вверх
Predator199
Дата 11.6.2014, 16:01 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 412
Регистрация: 1.2.2012

Репутация: -3
Всего: -4



Цитата(Aliance @ 11.6.2014,  14:20)
То, что ты пишешь, понять очень сложно! Пока ты не научишься писать грамотно, пользоваться спеллчекером и кнопкой "предварительный просмотр", тебе не смогут помочь, потому что понять, что ты написал - довольно сложно!

Посмотрите пожалуйста код.
Как сделать так, чтобы в классе public_downloads_post_submit. Можно было бы достать все те данные, которые получаем в классе  topicsLibrary.
Когда обращаемся к функции 
public function sortTopic
$this -> postt -> sortTopic( array_merge( $file, $save_array ), $category, $type );

В классе public_downloads_post_submit
Делаем обращение к функции sortTopic - функция находится в классе topicsLibrary. 
Итог, $this -> postt содержит класс  topicsLibrary. Но все, что внутри данного объекта(класса). Недоступно...

Код

public_downloads_post_submit Object ( [output:protected] => [sortTopic:protected] => [error_message:protected] => 
[_like:protected] => [paid_file_message:protected] => [postt] => topicsLibrary Object ( [post:protected] => classPost Object ( [class_attach] => [mo


$this -> postt -> post

итог
Fatal error: Cannot access protected property topicsLibrary::$post 
PM MAIL   Вверх
Aliance
Дата 11.6.2014, 16:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


I ♥ <script>
****


Профиль
Группа: Модератор
Сообщений: 6418
Регистрация: 2.8.2004
Где: spb

Репутация: 14
Всего: 137



Я уже давал ответ, зачем пытаться долбить одно и тоже?

1. Либо убрать protected  у переменной
2. Либо написать public метод, который возвращает переменную, и использовать его (предпочтительнее)
PM MAIL WWW ICQ Skype   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "PHP"
Aliance
IZ@TOP
skyboy
SamDark
MoLeX

Новичкам:

  • PHP редакторы собираются и обсуждаются здесь
  • Электронные книги по PHP, документацию можно найти здесь
  • Интерпретатор PHP, полную документацию можно скачать на PHP.NET

Важно:

  • Не брезгуйте пользоваться тегами [code=php]КОД[/code] для повышения читабельности текста/кода.
  • Перед созданием новой темы воспользуйтесь поиском и загляните в FAQ
  • Действия модераторов можно обсудить здесь

Внимание:

  • Темы "ищу скрипт", "подскажите скрипт" и т.п. будут переноситься в форум "Web-технологии"
  • Темы с именами: "Срочно", "помогите", "не знаю как делать" будут УДАЛЯТЬСЯ

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, IZ@TOP, skyboy, SamDark, MoLeX, awers.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | PHP: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0866 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.