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.

3

1 Answer 1

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'];
     }
  }
Sign up to request clarification or add additional context in comments.

3 Comments

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?"
using global cause debug nightmares since when you have much more code you will have no idea where a variable is defined.
@nurakantech do you go -1 all the answers that doesn't work for you, probably because your incompetency?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.