[英]Why am I getting NULL when I try to initiate a connection?
I have a class with global $connection
but when I try to access it I am getting NULL. 我有一个带有全局$connection
的类,但是当我尝试访问它时,我得到的是NULL。 As you can see if i try to access within the constructor I do not get NULL. 如您所见,如果我尝试在构造函数内访问,我不会得到NULL。 But from getConnection()
I am getting NULL. 但是从getConnection()
我得到NULL。
class DatabaseManipulation
{
private $connection;
function __construct()
{
global $connection;
$connection = new mysqli("localhost", "root", "", "db");
$result = $connection->query("select * from user");
print_r($result); //I get an array
}
function getConnection(){
global $connection;
var_dump($connection); // I get -> object(DatabaseManipulation)#1 (1) { ["connection":"DatabaseManipulation":private]=> NULL } NULL
}
}
Same thing happens when I instantiate an object $connection = new DatabaseManipulation();
当我实例化一个对象$connection = new DatabaseManipulation();
时,也会发生同样的事情$connection = new DatabaseManipulation();
. 。 Am I doing something wrong? 难道我做错了什么? I want this to be done in OO way. 我希望这可以通过OO方式完成。 Can anyone help me ? 谁能帮我 ?
You are using OO PHP not procedural. 您正在使用OO PHP而不是程序性的。 So change it to: 因此将其更改为:
$this->connection = new mysqli("localhost", "root", "", "db");;
I want this to be done in OO way. 我希望这可以通过OO方式完成。
Then stop using global
. 然后停止使用global
。 You don't want to refer to a global state when you're in a class. 在上课时,您不想引用全局状态。 A quick look to The Basics and you will find that a pseudo-variable $this
is available inside your object. 快速浏览The Basics ,您会发现在对象内部有一个伪变量$this
。
class DatabaseManipulation
{
private $connection;
function __construct()
{
$this->connection = new mysqli("localhost", "root", "", "db");
}
function getConnection(){
var_dump($this->connection);
}
}
More about it: 关于它的更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.