Ryan
Ryan

Reputation: 10049

PHP: Adding vars at runtime

Hey!
I have a local test server on my machine and my production server.
Instead of constantly editing my database credentials I want to include a db.php file that looks like this:

<?php

var $hostt = "localhost";
var $db_database = "testdb";
var $db_username = "root";
var $db_password= "";
?>

but when I try including it like this:

<?php

class testme{

include_once "db.php";

...

It refuses to work and spits out: Parse error: syntax error, unexpected T_INCLUDE_ONCE, expecting T_FUNCTION in

How can I get it to work the way I want to? Is it possible or am I barking up the wrong tree?

Thanks! R

Upvotes: 0

Views: 583

Answers (1)

TaylorOtwell
TaylorOtwell

Reputation: 7337

You can't execute an include statement outside of either the global scope or a function scope.

Move the include above your class declaration.

If you need access to those configuration options inside your class, try something like this.

// db.php

return array('host' => 'localhost', 'database' => 'testdb', etc);

// inside class function

$db_config = require 'db.php';

If you need it from many functions within the class. Set a class variable within your constructor:

class Something {

     public $config;

     public function __construct()
     {
          $this->config = require 'db.php';
     }

}

Upvotes: 5

Related Questions