Reputation: 7348
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;
}
}
Upvotes: 7
Views: 26189
Reputation: 11
You could use the $GLOBALS variable array and put your global variable as element in it.
For example: File: configs.php
<?PHP
$GLOBALS['config_key_security'] => "test";
?>
File: MyClass.php
<?php
require_once 'configs.php';
class MyClass {
function test() {
echo $GLOBALS['config_key_security'];
}
}
Upvotes: 1
Reputation: 2710
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;
}
}
Upvotes: 3
Reputation: 51668
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"];
}
}
?>
Upvotes: 16
Reputation: 722
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;
}
}
Upvotes: 5
Reputation: 2230
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.
Upvotes: 8
Reputation: 321698
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.
Upvotes: 22