2016-03-15 63 views
0

我试图整合用户的方式能够有配置设置保存到一个空白的PHP文件是这样的:PHP - 可以将Require_Once用作对象吗?

<?php // Configuration.php 
    $con = array(
     'host' => 'host' 
     'user' => 'username', 
     'pass' => 'password', 
     'name' => 'dbname' 
    ); 
?> 

我曾尝试:

class Configuration{ 

    public $database = require_once 'Configuration.php'; 

} 

$config = new Configuration; 
print_r($config->database->con); 

这是可能的或不?当访问Configuration.php页面时会出现一个显示,所以我不想include这个页面在这个网站上,只有require它的属性

在此先感谢。


Updated working code for viewers - 由@Yoshi使用类和构造函数的


的config.php -

if(defined('DFfdcxc58xasdGJWdfa5hDFG')): // Random unique security key 

    return array(
     'host' => 'localhost', 
     'user' => 'bob', 
     'pass' => '123', 
     'name' => 'data' 
    ); 

endif; 

数据库类:

interface Dashboard{ 

    public function initialize($actual); 

} 

define('DFfdcxc58xasdGJWdfa5hDFG',0); // Random unique security key 

class Configuration{ 

    protected $config = require_once('Config.php'); 
    protected $api_key = "Xc4FeSo09PxNcTTd3793XJrIiK"; 

} 

class DashboardSettings{ 

    public $alerts = array(); 
    protected $comments = true; 
    protected $read_only = false; 
    protected $safe_mode = false; 

} 

class Database extends Configuration extends DashboardSettings implements Dashboard{ 

    public function __construct(){ 
     $this->db = mysqli_connect($this->config[0],$this->config[1],$this->config[2],$this->config[3]); 
     if(mysqli_connect_errno){ array_push($this->alerts, 'Error connecting to Database...'); $this->safe_mode = true; } 
    } 

    public function initialize($actual = null){ 
     if($actual != null){ 
      // Handle incomming setting - reference DashboardSettings 
     } else { 
      // Handle all settings - reference DashboardSettings 
     } 
    } 

} 
+0

不,这是不可能的 –

+0

有什么办法来实现这一点,即使是在一个单独的方法? – KDOT

+1

加载配置并将其作为构造函数参数传递。 ('新配置($ con)') – Yoshi

回答

1

答案是否定的。当你分配require_once();一个变量,该变量变成与1的布尔以防文件已成功包括,否则返回0(在require_once(),因为它如果失败返回致命错误无用 所以,这样做:

<?php 
$hello = require_once("./hello.php"); 
echo $hello; // Prints 1. 
?> 

无论如何,如果你创建一个PHP文件,返回的东西,例如:

FILE: require.php 
<?php 
$hello = "HELLO"; 
return $hello; 
?> 

在这种情况下,前面的例子是不同的:

<?php 
$hello = require_once("./require.php"); 
echo $hello; // Prints HELLO. 
?> 

因此,您不能将函数本身存储为稍后执行,但可以存储所需文件或包含文件中的返回值。无论如何,如果你更好地解释你使用它的原因,我可能会更好地帮助你。

回答@大卫阿尔瓦雷斯

+0

因此,如果我在配置文件中添加了'return $ con;',那么我的'print_r'应该可以工作吗?非常感谢! - 哈哈,完美。这工作! – KDOT

+0

@ KyleE4K如果你去使用'return',请不要'返回$ con',因为这个'$ con'变量会在你的需要的脚本中出现。只需使用'return array(...);'。而小挑逗,'require_ *'(和类似的)是语句,而不是函数。删除括号;) – Yoshi

+0

我已经使用'define()'作为安全性;)我很欣赏这个评论,并且已经完成了'return array(...)'并且就像你说的那样在我的构造函数中停留:P @耀西 – KDOT