Search code examples
phpcodeigniterclassincludeprivate

PHP class private variable set from different (included) file


I have a class that uses private variables those variables are "configuration variables", and I need them to "change" sometimes (in my example if I add new language I need to have in config also new language it's i18n library for CodeIgniter.

I need to set $languages and $special from database.

class MY_Lang extends CI_Lang {
  // languages
  private $languages = array(
    'en' => 'english',
    'sk' => 'slovak',
    'fr' => 'french',
    'nl' => 'dutch'
  );

  // special URIs (not localized)
  private $special = array (
    "admin",
    "link"
  );
.
.
.
  function MY_Lang()
  {
    parent::__construct();
.
.
.

My thought is that I generate a file and include it in the library.

As follows: I've tried this, so script will generate file language_config.php each time whenever administrator says to.

class MY_Lang extends CI_Lang {
  public function __construct()
  {
    parent::__construct();
    include_once(APPPATH.'/config/system_generated/language_config.php');

    // languages
    $languages = $generated['languages'];

    // special URIs (not localized)
    $special = $generated['special'];
  }

and generated file

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
  // languages
  $generated['languages'] = array(
    'en' => 'english',
    'sk' => 'slovak',
    'fr' => 'french',
    'nl' => 'dutch'
  );

  // special URIs (not localized)
   $generated['special'] = array (
    "admin",
    "link"
  );

I am not asking how to generate file but how to include and use included file inside library file (and set variables as private). I can not set private variables inside constructor is there any way to set included variables as private?

EDIT: SOLUTION

I forgot about private rules and the whole OOP $this->..., code below works fine.

class MY_Lang extends CI_Lang {

private $languages;
private $special;

  public function __construct()
  {
    parent::__construct();
    include_once(APPPATH.'/config/system_generated/language_config.php');

    // languages
    $this->languages = $generated['languages'];

    // special URIs (not localized)
    $this->special = $generated['special'];
  }

EDIT2: another problem with this

As I added new __constructor() to my class, it causes problem because it does not call __constructor() from CI_Lang for some reason even in my "added" __constructor() there is parent::__constructor(); which should call CI_Lang __construcotr(), but it does not. I don't even know how to debug this.

SOLUTION to EDIT2

I had 2 constructors in my code. Just merge them.


Solution

  • Set them in the construct method __construct(), like this:

    private $languages;
    private $special;
    
    public function __construct()
    {
        $this->languages = $generated['languages'];
        $this->special = $generated['special'];
    }