tags:

views:

690

answers:

5

i have some file test.php

<?PHP
    $config_key_security = "test";
?>

and i have some class

test5.php

 include test.php
       class test1 {
                function test2 {
                   echo $config_key_security;
             }
        }
+6  A: 
   class test1 {
            function test2 {
               global $config_key_security;
               echo $config_key_security;
         }
    }

or

   class test1 {
            function test2 {
               echo $GLOBALS['config_key_security'];
         }
    }

Having your class rely on a global variable isn't really best practice - you should consider passing it in to the constructor instead.

Greg
+3  A: 

Another option is to include test.php inside of the test2 method. That will make the variable's scope local to the function.

   class test1 {
            function test2 {
               include('test.php');
               echo $config_key_security;
         }
    }

Still not a good practice though.

Matt
So long as it is not abused, this is a very useful way of allowing run-time configuration of classes. It also allows you to separate program logic from presentation by pulling the "template" portion of a function out and placing it in an include.
Jeff Ober
A: 

Using __construct() method.

include test.php;
$obj = new test1($config_key_security);
$obj->test2();

class test1
{
    function __construct($config_key_security) {
        $this->config_key_security = $config_key_security;
    }

    function test2() {
        echo $this->config_key_security;
    }
}
StackKrish
A: 

Have your config file create an array of config items. Then include that file in your class's constructor, and save its value as a member variable. This way, all your config settings are available to the class.

test.php:

<?
$config["config_key_security"] = "test";
$config["other_config_key"] = true;
...
?>

test5.php:

<?
class test1 {
    private $config;

    function __construct() {
        include("test.php");
        $this->config = $config;
    }

    public function test2{
        echo $this->config["config_key_security"];
    }
}
?>
JW
A: 

the way I prefer to do it is this:

In test.php

define('CONFIG_KEY_SECURITY', 'test');

and then:

in test5.php

include test.php
   class test1 {
            function test2 {
               echo CONFIG_KEY_SECURITY;
         }
    }
JSD