Steve L
Steve L

Reputation: 1635

PHP class unable to access included variables

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.

Upvotes: 0

Views: 2133

Answers (1)

DevZer0
DevZer0

Reputation: 13525

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'];
     }
  }

Upvotes: 2

Related Questions