[英]How to Include Variable inside Class in php
我有一些文件test.php
<?PHP
$config_key_security = "test";
?>
我有一些課
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;
}
}
要么
class test1 {
function test2 {
echo $GLOBALS['config_key_security'];
}
}
讓你的類依賴於全局變量並不是最佳實踐 - 你應該考慮將它傳遞給構造函數。
讓配置文件創建一個配置項數組。 然后在類的構造函數中包含該文件,並將其值保存為成員變量。 這樣,您可以使用所有配置設置。
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"];
}
}
?>
另一種選擇是在test2方法中包含test.php。 這將使變量的范圍成為函數的本地范圍。
class test1 {
function test2 {
include('test.php');
echo $config_key_security;
}
}
盡管如此仍然不是一個好習慣。
我喜歡這樣做的方式是這樣的:
在test.php中
define('CONFIG_KEY_SECURITY', 'test');
接着:
在test5.php中
include test.php
class test1 {
function test2 {
echo CONFIG_KEY_SECURITY;
}
}
使用__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;
}
}
您可以使用$ GLOBALS變量數組並將全局變量作為元素放入其中。
例如: File:configs.php
<?PHP
$GLOBALS['config_key_security'] => "test";
?>
文件:MyClass.php
<?php
require_once 'configs.php';
class MyClass {
function test() {
echo $GLOBALS['config_key_security'];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.