5

For example I have file config.php:

$host = 'localhost';
$db = 'logger';
$user = 'user';
$pwd = 'pass';

and file mysqlClass.php

class mysql{

public function connect(){

//hot get get variables form confing.php there ?
}

}

And I not know hot to get variables from confin.php in mysql class, I can't change config.php file

4
  • 1
    Pass the variables through a function, or call them globally. Google that information. Commented Apr 22, 2013 at 19:11
  • pass them to the constructor of the class. Commented Apr 22, 2013 at 19:13
  • Do not use the mysql_ database functions; use something like PDO instead. php.net/manual/en/book.pdo.php Commented Apr 22, 2013 at 19:13
  • 1
    Possible repeat stackoverflow.com/questions/5799267/… Commented Apr 22, 2013 at 19:13

3 Answers 3

5

Just require_once() the file

public function connect() {
  require_once 'config.php';
  // ...code...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Also a possible way, but including files in functions (apart from autoloader), is this good style?
3

Use function parameters:

class mysql{
    public function connect($host, $db, $user, $pass){
        // do something with the variables
    }
}

When instantiating mysql now, use:

require 'config.php';
$mysql = new mysql($host, $db, $user, $pass);

2 Comments

This is a better solution, in line with what object-oriented code should be. Don't use the require_once thing within your Mysql class.
That's exactly what I commented to @bsdnoobz
2
include 'config.php';
include_once 'config.php';

or

require 'config.php';
require_once 'config.php';

Inside of mysqlClass.php

The difference between include and require is that require will also produce a fatal E_COMPILE_ERROR level error, stopping the script, whereas, include only produces E_WARNING, which will NOT stop the script. The difference between include_once or require_once and include or require is that PHP will check to see if the file has been included already, and if it hasn't, it will include it. If it has, it will not load it again.

Comments

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.