我有一些文件test.php
<?PHP
$config_key_security = "test";
?>
Run Code Online (Sandbox Code Playgroud)
我有一些课
test5.php
include test.php
class test1 {
function test2 {
echo $config_key_security;
}
}
Run Code Online (Sandbox Code Playgroud)
Gre*_*reg 19
class test1 {
function test2 {
global $config_key_security;
echo $config_key_security;
}
}
Run Code Online (Sandbox Code Playgroud)
要么
class test1 {
function test2 {
echo $GLOBALS['config_key_security'];
}
}
Run Code Online (Sandbox Code Playgroud)
让你的类依赖于全局变量并不是最佳实践 - 你应该考虑将它传递给构造函数.
JW.*_*JW. 15
让配置文件创建一个配置项数组.然后在类的构造函数中包含该文件,并将其值保存为成员变量.这样,您可以使用所有配置设置.
test.php的:
<?
$config["config_key_security"] = "test";
$config["other_config_key"] = true;
...
?>
Run Code Online (Sandbox Code Playgroud)
test5.php:
<?
class test1 {
private $config;
function __construct() {
include("test.php");
$this->config = $config;
}
public function test2{
echo $this->config["config_key_security"];
}
}
?>
Run Code Online (Sandbox Code Playgroud)
另一种选择是在test2方法中包含test.php.这将使变量的范围成为函数的本地范围.
class test1 {
function test2 {
include('test.php');
echo $config_key_security;
}
}
Run Code Online (Sandbox Code Playgroud)
尽管如此仍然不是一个好习惯.
使用 __construct() 方法。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18634 次 |
| 最近记录: |