tags:

views:

104

answers:

2

What I am trying to do is have a separate PHP file containing settings for the website, and then having other pages include this file and execute code according to the settings. However, whenever I use global to reference these variables inside a class, the variables are empty. For example:

settings.php:

<?php
$setting1 = 'on';
$setting2 = 'off';
?>

class.php:

<?php
require_once('./settings.php');

class myclass {
  public function __construct {
    global $setting1;
    echo $setting1;
  }
}

$object = new myclass;
?>

This prints nothing. However, if I do "echo $setting1" outside of the class, it prints 'on'. When I tried setting the variable inside the file itself rather than including it, in printed 'on' when I created a new object for myclass. Is there something special I need to do to make the included variables available in the global scope for the class?

+8  A: 

Your constructor needs brackets after its name, e.g.

public function __construct() {

}

I suspect this is giving you a fatal error and that is not being shown because of your display_errors / error_reporting settings.

Tom Haigh
+1 - well spotted.
karim79
Nice, very quick! :)
Mark L
Thanks. I added this, however I'm still facing the same problem: included variables aren't available in the global scope for the class.
Scootz
+1  A: 

You were missing the parentheses:

public function __construct {

should be

public function __construct( ) {

Result:

$ php -v
PHP 5.2.5 (cli) (built: Nov 29 2007 09:31:38) 
2007-Macbook:Desktop mark$ php class.php
on
Mark L