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条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试