2016-03-15 64 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