CodeIgniter; $this usage in non object context

2019-04-13 02:55发布

问题:

I am trying to edit my config/database.php within my CodeIgniter project so that I don't have to keep changing the database information every time I push a new version to the server. To do the latter, I have created a $debug variable, shown below, which checks against the uri to see if the site is being run on my localhost machine (where I build the project before upload) or on the actual server.

Unfortunately in the database.php file, I don't have access to the $this variable, and as I am personally new to OOP in PHP, I am not entirely sure of a way around this. Please can you tell me how I can do so?

Thanks,

Max.

Fatal error: Using $this when not in object context in application/config/database.php on line 51

$debug = strpos($this->uri->config->item('base_url'), 'localhost'); //line 51

$db['default']['hostname'] = $debug == TRUE ? 'x' : 'y';
$db['default']['username'] = $debug == TRUE ? 'x' : 'y';
$db['default']['password'] = $debug == TRUE ? 'x' : 'y';
$db['default']['database'] = $debug == TRUE ? 'x' : 'y';

回答1:

You need to a get an instance of the codeigniter object -

$CI = get_instance();

For older versions of php, use =&

Then, use $CI wherever you would normally use $this



回答2:

You need to use get_instance() to get the $this variable.

$ci = get_instance(); // $ci replaces $this
echo $ci->config->item('base_url');

The $this variable is a special variable used in object oriented code, when you have classes - see php.net for some background reading on it.



回答3:

$this is only for objects, you cannot use it outside an object. Best way to do this, I believe, is to exclude database.php file when you deploy. The IDE you use should have an option to exclude file from deployment.



回答4:

There's a simple answer to this problem.

Read Environment section at: http://codeigniter.com/user_guide/libraries/config.html

basically create two folders application/config/production and application/config/development

and put one copy of your database.php in each folder.



回答5:

You can also use $_SERVER['SERVER_NAME'] and compare it with your server names (localhost or remote). There is a function in CI that checks for it:

$this->input-> server('SERVER_NAME')

As written above, you have to change the this if not in object context.