【问题标题】:PHP get variables in class from another filePHP从另一个文件中获取类中的变量
【发布时间】:2013-04-22 19:10:02
【问题描述】:

例如我有文件config.php:

$host = 'localhost';
$db = 'logger';
$user = 'user';
$pwd = 'pass';

并归档mysqlClass.php

class mysql{

public function connect(){

//hot get get variables form confing.php there ?
}

}

而且我不知道如何从 mysql 类中的 confin.php 获取变量,我无法更改 config.php 文件

【问题讨论】:

标签: php oop class


【解决方案1】:
include 'config.php';
include_once 'config.php';

require 'config.php';
require_once 'config.php';

mysqlClass.php内部

includerequire 的区别在于require 也会产生致命的E_COMPILE_ERROR 级别错误,停止脚本,而include 只产生E_WARNING,不会停止脚本. include_oncerequire_onceincluderequire 之间的区别在于 PHP 将检查文件是否已经包含,如果没有,它将包含它。如果有,它将不会再次加载。

【讨论】:

    【解决方案2】:

    只需require_once() 文件

    public function connect() {
      require_once 'config.php';
      // ...code...
    }
    

    【讨论】:

    • 也是一种可能的方式,但是在函数中包含文件(除了自动加载器),这样的风格好吗?
    【解决方案3】:

    使用函数参数:

    class mysql{
        public function connect($host, $db, $user, $pass){
            // do something with the variables
        }
    }
    

    现在实例化mysql 时,使用:

    require 'config.php';
    $mysql = new mysql($host, $db, $user, $pass);
    

    【讨论】:

    • 这是一个更好的解决方案,符合面向对象的代码应该是什么。不要在你的 Mysql 类中使用 require_once 。
    • 这正是我对@bsdnoobz 的评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多