Page 1 of 1

Vaiable Scope

Posted: Wed Oct 13, 2004 5:03 pm
by partiallynothing
I have a nice library of classes. Many of them require config variables, which i passed to them via the constructor. Example:

Code: Select all

<?php
$config_vars['project_title'] = "Example Project";
$config_vars['project_version'] = "0.6";
$config_vars['db_user'] = "Example DB User";
$config_vars['db_pass'] = "Example DB Pass";
$config_vars['db_name'] = "Example DB Name";
$config_vars['db_host'] = "localhost";

class example {

  public $config_vars

  public function __construct ($config_vars){
    $this->config_vars = $config_vars;
  }

  public function dplyConfVars() {
    foreach ($config_vars as $index => $value) {
      echo $index . ' => ' . $value . '<br>';
    }
  }
}
?>
This has become very tidiouse and sometimes gets in the way. Is there any way I can call a variable from within a class that was defined outside of a class? Example:

Code: Select all

<?php
class example {

  public function __construct(){
  }

  public function dplyConfVars() {
    global $config_vars;
    foreach ($config_vars as $index => $value) {
      echo $index . ' => ' . $value . '<br>';
    }
  }
}
?>
I have only know "global" to work with functions, such as

Code: Select all

<?php
function changeVar($new_var) {
  global $var;
  $var = $new_var;
}

$var = 1;
echo $var; //displays 1
changeVar(5);
echo $var; //displays 5
?>
Is there anything like the above that will work with classes? Thanks!

Posted: Wed Oct 13, 2004 5:08 pm
by kettle_drum
Well why not harness some of the power of OO and inherit a base class to deal with all that:

Code: Select all

class myBaseClass {
   var $config = array();

   function __constructor(&$config){
      $this->config = $config;;
   }
}

class blah extends myBaseClass {
//my methods
}
Then you dont have to do anything unless you want the child class to have a constructor - inwhich case you just call the parent constructor from within that.

Simple.

Posted: Wed Oct 13, 2004 5:14 pm
by partiallynothing
I thought of that myself, but my code base is too large to try and do such. Any other ideas?

Posted: Thu Oct 14, 2004 2:50 am
by CoderGoblin
If the variables are fixed (per customer for instance) have you thought of using an initialisation file?

http://www.php.net/function.parse-ini-file

Posted: Thu Oct 14, 2004 3:07 am
by phpScott
you could always put your config variables on another page then just include them within your class.
I do that for my db class so I can use the same class and send the constructor the name of the file I want to include. the db class includes the right file and that file has the username, password, db name etc... in it.