douye5949 2014-03-20 17:29
浏览 28
已采纳

ALL的一个连接,OOP PHP

struggling to grip the varying levels of variables in OOP PHP. I want to have one connection file which can be accessed from all classes and functions through out my project. I include 'config.php' but the $mysql variable cannot be found. Any help greatly appreciated;

I have a file

config.php

public $mysqli = new mysqli('localhost', 'usernameEG', 'passwordEG', 'databaseEG');

if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
    }

and a few class files

class.User.php

<?php

class User {

private $mysqli = null;

function __construct(){

    //=========
//include config.php  here?
    }

function myProfile($Id){

$stmt = $this->mysqli->prepare("SELECT First_Name, Last_Name, Email, DateJoined FROM members WHERE Id = ? ");
$stmt->bind_param('i',$Id);
$stmt->execute();
$stmt->bind_result($fname,$lname,$email,$date);
$stmt->store_result();
$stmt->fetch();

        echo "<p>User#: ".$Id."</p>";
        echo "<p>First Name: ".$fname."</p>";
        echo "<p>Last Name: ".$lname."</p>";
        echo "<p>Email: ".$email."</p>";
        echo "<p>Date Joined: ".$date."</p>";
        $stmt->close();

}
function example(){
EXAMPLE CODE HERE WILL ALSO NEED TO BE ABLE TO USE SAME CONNECTION
}

}
  • 写回答

2条回答 默认 最新

  • dongrou5254 2014-03-20 17:58
    关注

    So rather than a singleton approach as hinted at in the other answer. Let me offer you a dependency injection approach. For a lot of experienced developers, dependency injection is a preferred approach, as it allows the class receiving the dependency to have looser coupling to the dependency (for example, you don't need to even know the name of the class for instantiating the dependency like you would with a singleton approach). You just need to know that the dependency being passed meets some interface requirement (i.e. it implements some interface or is a certain type of class).

    So that would look more like this:

    class User {
        protected $mysqli = null;
    
        // other properties
    
        public function __construct(mysqli $mysqli) {
            $this->mysqli = $mysqli;
            // other constructor operations
        }
    
        // other methods
    }
    

    So what is happening here? Here you enforce the requirement to pass an object of type mysqli when instantiating this class. This could be a mysqli object or perhaps even your own custom class which extends mysqli, the User class doesn't care, so long as all mysqli class methods are implemented

    Usage could be like

    require('/path/to/db_config.php'); // an include which creates a mysqli object or provides a factory for one, or whatever
    $user = new User($mysqli);
    $user->foo(); // do something
    

    Interestingly enough, you might at times see use of singelton pattern along with dependency injection. So say you had a mysqli_singleton_factory class with singleton functionality to provide you the single instantiated mysqli object. The usage might look like this:

    require('/path/to/db_config.php'); // an include which provides a singleton
    $user = new User(mysqli_singleton_factory::get_instance());
    $user->foo(); // do something
    $other_class = new other_class_requiring_mysqli(mysqli_singleton_factory::get_instance());
    $other_class->bar(); // do something
    

    Here you have both guaranteed that you only have one instantiated mysqli object during script execution AND you have decoupled your User class from having to do any instantiation of the object itself.

    For reference, a singleton pattern may look like this:

    class mysqli_singleton_factory {
        protected static $mysqli = null;
    
        protected function __construct() {
            // assume DB connection setting have been pre-defined as constants somewhere
            $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            // make sure connection worked
            if($mysqli->connect_error) {
                throw new Exception(__METHOD__ . ' at line ' . __LINE__ . ' failed with: ' . $mysqli->connect_error);
            }
            self::mysqli = $mysqli;
        }
    
        public static function get_instance() {
            if (false === self::mysqli instanceof mysqli) {
                self::__construct();
            }
            return self::mysqli;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1