dsfsdfsdfsdf6455 2013-10-10 18:09
浏览 43

在PHP对象中包含全局变量

Hopefully this is a straight forward question:

I am looking to create a class, and I want to include my database variable ($mysql) in it so I can do DB interactions. So far, I've been making it global inside functions, but I'm hoping that rather then including the variable globally in every class function, there was some way to simply include it into the class/access it in the class. I'm not very good with scoping.

The only option I can think of is to create a class variable and in the constructor, include the variable globally and assign it (maybe by reference, does that make sense?) to the class variable.

Any other options?

  • 写回答

1条回答 默认 最新

  • doudeng2016 2013-10-10 18:18
    关注

    I programmed this class for my database handling, maybe its a bit of use to you:

    <?php
        class Database {
            public $mysqli;
    
            function __construct() {
                $this->connect();
            }
    
            function __wakeup() {
                $this->connect();
            }
    
            function connect() {
                $mysqli = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB);
                if ($mysqli->connect_error) {
                    die('Connect Error (' . $mysqli->conect_errno . ')'
                        . $mysqli->connect_error);
                }
                mysqli_set_charset($mysqli, 'utf8');
                $this->mysqli = $mysqli;
            }   
    
            function queryDB($query) {
                $result = $this->mysqli->query($query);
    
                if ($this->mysqli->error) {
                    error_log("QUERY ERROR: " .$this->mysqli->error);
                    error_log("QUERY: " . $query);
                }
                return $result;
            }
        }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题