CodeIgniter Forums
get variable from the same class - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: get variable from the same class (/showthread.php?tid=34309)



get variable from the same class - El Forum - 09-25-2010

[eluser]Avril[/eluser]
Hello,

I have class called Blog_model that gets all my blog posts from the database.
This works like a charm, so here's my code:

Code:
<?php

class Blog_model extends Model{

    function getBlogPosts(){
        
        $this->db->select('title, author, content, date_posted');
        $this->db->from('lm_blog_posts');
        $this->db->where('type', 3);
        $q = $this->db->get();
        
        if( $q->num_rows() >= 1){
            foreach( $q->result() as $row ){
                $data[] = $row;
            }
            return $data;
        }
        
    }
    
    function splitTitle(){
    
        
    
    }
    
}

Now I have made a second function that will split the Title for design purposes.
So, how do I get the array from the getBlogPosts function into my splitTitle function?

Something like this?:

Code:
$this->getBlogPosts['title']



get variable from the same class - El Forum - 09-25-2010

[eluser]WanWizard[/eluser]
You will have to make a design decision:

You can add title splitting logic to getBlogPosts().

You can create splitTitle() so that it expects a data array, and then use this in your controller:
Code:
$data = $this->Blog_model->splitTitle( $this->Blog_model->getBlogPosts() );

or create splitTitle() so that it expects a string 'title', and then use this in your controller:
Code:
$data = $this->Blog_model->getBlogPosts();
foreach ( $data as $key => $value )
{
   $data[$key]['title'] = $this->Blog_model->splitTitle( $value['title'] );
}

You can also code splitTitle() to be an enhancement to getBlogPosts(). Have splitTitle() call getBlogPosts(), loop over the result like above, and return the array with converted titles.

Plenty of options to choose from... I would go for the last option. Keep it clean, and all data processing in the model.


get variable from the same class - El Forum - 09-25-2010

[eluser]Avril[/eluser]
Hey, thanks for the reply.

Well I'm planning to keep the code in de model, that's why I created the splitTitle function.
But I don't know how to call the getBlogPosts function from within the same model. Is it something like:
Code:
$this->blog_model->getBlogPosts()
??


get variable from the same class - El Forum - 09-25-2010

[eluser]WanWizard[/eluser]
It's a method local to the class, so
Code:
$data = $this->getBlogPosts();
will do. No CI magic involved.


get variable from the same class - El Forum - 09-25-2010

[eluser]Avril[/eluser]
damn your right, it's OOP PHP .. D'oh!