Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter pass params to function

I'm new to OOP and I'm having some trouble on understanding the structures behind it. I've created a library in Codeigniter (Template), which I pass some parameters when loading it, but I want to pass those parameters to the functions of the library.

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

class Template {

    public function __construct($params)
    {
        echo '<pre>'; print_r($params); echo '</pre>';
        //these are the parameters I need. I've printed them and everything seems fine
    }

    public function some_function()
    {
        //I need the above parameters here
    }

}
like image 860
AFRC Avatar asked Feb 25 '23 06:02

AFRC


1 Answers

Try this:

class Template {

    // Set some defaults here if you want
    public $config = array(
        'item1'  =>  'default_value_1',
        'item2'  =>  'default_value_2',
    );
    // Or don't
    // public $config = array();

    // Set a NULL default value in case we want to use defaults
    public function __construct($params = NULL)
    {
        // Loop through params and override defaults
        if ($params)
        {
            foreach ($params as $key => $value)
            {
                $this->config[$key] = $value;
            }
        }
    }

    public function some_function()
    {
        //i need the above parameters here

        // Here you go
        echo $this->config['item1'];
    }

}

This would turn array('item1' => 'value1', 'item2' => 'value2'); into something you can use like $this->config['item1']. You are just assigning the array to the class variable $config. You could also loop through the variables and validate or alter them if you wish.

If you don't want to override the defaults you set, just don't set the item in your $params array. Use as many different variables and values as you want, it's up to you :)

As Austin has wisely advised make sure to read up on php.net and experiment yourself. The docs can be confusing because they give a lot of edge case examples, but if you check out the Libraries in Codeigniter you can see some examples or how class properties are used. It's really bread-and-butter stuff that you must be familiar with to get anywhere.

like image 174
Wesley Murch Avatar answered Feb 26 '23 20:02

Wesley Murch