简体   繁体   中英

How to Include Variable inside Class in php

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;
             }
        }
   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.

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"];
    }
}
?>

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.

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;
         }
    }

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;
    }
}

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'];
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM