0

This is a PHP newbie question:

I want to give my class access to my database credentials in an include file: ../config.inc

<?php
   $db_info['host']='localhost'; // and so forth 
   ...
 ?>

Later, in my class source file I have:

   <?php
      require_once('../config.inc'); // include the above file
      public class Foo {
         static function Host() {
            echo $db_info['host'];
         }
      }
   ?>

When try to access the class in other code, I get an error claiming that $db_info is undefined. When I try to move the require_once inside the class scope (after Foo {) I get a syntax error, so apparently one can't use require_once inside the class. What are the best practices when writing class static methods that need access to included data? THANKS.

Steve L
  • 1,523
  • 3
  • 17
  • 24
  • Pass `$db_info` to the constructor of `Foo`. – Dave Chen Aug 29 '13 at 03:33
  • possible duplicate of [Variable scope in PHP class](http://stackoverflow.com/questions/16509077/variable-scope-in-php-class) – mario Aug 29 '13 at 03:33
  • [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](http://stackoverflow.com/q/16959576) – mario Aug 29 '13 at 03:34

1 Answers1

2

You have a issue with the scope. Your included variable is available outside your class but not inside your class. The suggested methods should be to pass the variable to the constructor of your class and store it in a member variable of the class.

But since your using the function as static then you can use global but its not best practices to do so. alternatively you can include the file with in the function.

  public class Foo {
     static function Host() {
      require_once('../config.inc'); // include the above fil  
      echo $db_info['host'];
     }
  }
DevZer0
  • 13,433
  • 7
  • 27
  • 51
  • for some reason, the require inside the class didn't work, but I didn't try putting it inside the function. I'll give that a try too. Any thoughts why just using global isn't "best practice?" – Steve L Aug 29 '13 at 04:12
  • 1
    using `global` cause `debug` nightmares since when you have much more code you will have no idea where a variable is defined. – DevZer0 Aug 29 '13 at 04:20
  • @nurakantech do you go -1 all the answers that doesn't work for you, probably because your incompetency? – DevZer0 Feb 20 '14 at 02:09