php oop 变量作用域 [英] php oop variable scope

查看:52
本文介绍了php oop 变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个类.. 在它的构造函数中,我包含了通过 mysqli 扩展将我连接到我的数据库的代码:

So I have a class.. In its constructor I include the code which connects me to my database via the mysqli extension:

class MyClass
{
    public function __construct()
    {
        include("dbconnect");
    }
}

dbconnect 看起来像这样:

dbconnect looks like this:

$host = "localhost";
$user = "user";
$pass = "123";
$database = "myDatabase";

$mysqli = new mysqli($host, $user, $pass, $database);
$mysqli->set_charset('utf8-bin');

现在我的问题:既然mysqli可以使用OOP-Style,我如何访问MyClass中的变量?

Now to my problem: Since mysqli can be used OOP-Style, how do I get access to the variable in MyClass?

function doIt()
{    
    $query = "SELECT * FROM myTable";    
    $result = $mysqli->multi_query($query);
}

调用这个函数会导致

注意:未定义变量:mysqli in... 在线的 ...致命错误:在非对象上调用成员函数 multi_query()在...在线...

Notice: Undefined variable: mysqli in ... on line ... Fatal error: Call to a member function multi_query() on a non-object in ... on line ...

所以好像变量的作用域不对.有谁知道如何解决这一问题?如果 MyClass 不需要额外的引用或 mysqli 的东西,那将是最好的,因为我想将它分开.

So it seems the scope of the variable is not right. Does anyone know how to fix this? It would be best if MyClass would not need an extra reference or something to mysqli, since I would like to keep it seperated.

推荐答案

$mysqli 变量仅在构造函数范围内可用.像这样改变你的构造函数:

The $mysqli variable is only available inside the scope of the constructor. Change your constructor like so:

class MyClass
{
    public function __construct()
    {
        include("dbconnect");
        $this->mysqli = $mysqli;
    }
}

现在您可以在该对象的其他方法中使用 $this->mysqli.

Now you can use $this->mysqli in other methods on that object.

这篇关于php oop 变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆