CodeIgniter Forums
Php 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: Php class (/showthread.php?tid=44069)



Php class - El Forum - 08-01-2011

[eluser]nuclearmaker[/eluser]
hi, i want to create the some CI library,
so here is my code.
but 2 diff method, i need to call the instance again.is there a way to call once only?

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once('SomeClass.php');

public function title()
{
    $html = new SomeClass();
    
    return $html->title;
}

public function body()
{
    // here i need to call the instance again.is there a way to call once only?
    $html = new SomeClass();
    
    return $html->body;
}



Php class - El Forum - 08-02-2011

[eluser]LuckyFella73[/eluser]
I guess you have to load the library in your class contructor:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Yourclass
{
    public function __construct()
    {
        require_once('SomeClass.php');
        $this->html = new SomeClass();
    }

    

    public function title()
    {
        return $this->html->title;
    }

    public function body()
    {
        return $this->html->body;
    }

}



Php class - El Forum - 08-02-2011

[eluser]danmontgomery[/eluser]
Libraries in CI are just classes, why not stick it in the libraries folder and use the loader?

Code:
class Yourclass
{
    public function __construct()
    {
        $CI = get_instance();
        $CI->load->library('html');
        $this->html = $CI->html;
    }

    

    public function title()
    {
        return $this->html->title;
    }

    public function body()
    {
        return $this->html->body;
    }

}