and i have a class test5.ph...">

How to include a variable inside a class in php

I have a test.php file

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

and i have a class

test5.php

  include test.php class test1 { function test2 { echo $config_key_security; } } 
+4
source share
6 answers
  class test1 { function test2 { global $config_key_security; echo $config_key_security; } } 

or

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

If your class relies on a global variable, this is actually not the best practice - you should consider passing it to the constructor instead.

+16
source

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

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

However, this is not a good practice.

+7
source

Create your configuration file an array of configuration items. Then include this file in your class constructor and save its value as a member variable. Thus, all your configuration settings are available for 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"]; } } ?> 
+7
source

Using the __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; } } 
+2
source

as I prefer to do 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; } } 
+1
source

You can use the $ GLOBALS array of variables and put your global variable 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']; } } 
+1
source

All Articles