Sunday, 15 July 2012

php - variables in config file are not available in class -


I have a simple question, but I am unable to resolve it. I have a config file in which the variables are formatted:

  $ config ['something'] = 'value';  

This file is being included in an index.php, where I have an __autoload function. All work is fine, the config file is available within index.php (I can output each value) and when I start a class or call a static object, the autoloader does the job.

The problem is that I try to use those configuration values ​​as logical as I have loaded and I get an "undefined variable: config" error for each of them. What am i doing

config.php

  $ config ['item1'] = 'value1'; $ Config ['item2'] = 'value2'; $ Config ['item3'] = 'value3';  

index.php

  need_once ('config.php'); Function __autoload () ...  

class.mysql.php

  function connect () {mysqli_connect ($ connect [ 'Host'] etc. ....  

Obviously, above is a simplified version of what I am doing to clarify the relationship between the files. How do I configure variables in config .php should be available in a category which is autoloaded?

Thanks!

You are facing the issue of a scope that The C function is not accessible within the built-in variable, and the variables created within a function are not accessible outside of it.

More info here:

You have two solutions

  1. Pass the $ config array in the function as argument

Index.php

  need_once ('config.php'); function __autoload ($ config) ...  

class.mysql .php < / Strong>

  function   
  1. Use global

    Index.php

      need_once ('config.php'); Function __autoload () ...  

    class.mysql.php

      connect the function () {// if you want Are $ Config variables to use in the global $ config; Mysqli_connect ($ ['host'] etc. can be connected to.  

    See it in action:

    Personally I like to use the solution first Because it helps me understand it easier than come from the $ config variable


No comments:

Post a Comment