当我尝试在 PHP 中访问它时,类变量为空 [英] Class variable is null when I try to access it in PHP

查看:49
本文介绍了当我尝试在 PHP 中访问它时,类变量为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是我的主要代码:

require "checkpassword.php";需要mysqllogininfo.php";# 验证密码if (!validatePassword($_GET["password"])) {返回;}# 获取变量$uuid = $_GET["uuid"];if (preg_match('/^\d+$/',$_GET["rank"]) == false) {die("等级必须是整数");}$rank = $_GET["rank"];# 验证 UUID如果($uuid == null){死(供应uuid");}# 验证排名如果($rank == null){死(供应等级");} else if ($rank <0 || $rank > 6) {死(无效等级");}# 加载 MySQL 登录信息$loginInfo = new MySQLLoginInfo("/var/uniqraft/mysqllogin");# 调试# 所有这些都显示为 3 个空行,所以我假设变量为空 <--echo($loginInfo->host);echo "
";echo($loginInfo->用户名);echo "
";回声($登录信息->密码);echo "
";echo($loginInfo->dbname);# 创建连接$connection = mysqli_connect($loginInfo->host, $loginInfo->username, $loginInfo->password, $loginInfo->dbname);# 检查连接如果(mysqli_connect_errno()){die("连接MySQL失败:" .mysqli_connect_error());}

如您所见,我正在尝试访问 MySQLLoginInfo 对象中的变量 host、username、password 和 dbname,但它们都显示为 null.

然而,我不认为它们实际上是空的.因为,如果我们查看 MySQLLoginInfo 对象,我们可以看到我添加了一些调试 echo() 来显示变量,并且在那里我们看到它们实际上不为空.

class MySQLLoginInfo{# 特性公共 $host;公共 $ 用户名;公共 $password;公共 $dbname;# 构造函数函数 __construct($infoLocation) {$handle = fopen($infoLocation, "r", false) or die("Couldn't open $infoLocation");$i = 0;# 遍历行while (($line = fgets($handle)) !== false) {如果 ($i === 0)$host = $line;否则如果 ($i === 1)$username = $line;否则如果 ($i === 2)$password = $line;否则如果 ($i === 3)$dbname = $line;别的休息;# 最多读取 4 行$i++;}如果 ($i <3) {die($infoLocation ." 不包含至少 4 行");}# 这些都显示正确的值,说明它们不为空 <--回声 $host;回声 $ 用户名;回声$密码;回声 $dbname;}}

最终输出如下:

<块引用>

本地主机 mcserver secret_password uniqraft_core

无法连接到 MySQL:用户 'www-data'@'localhost' 的访问被拒绝(使用密码:NO)

请注意,主代码中 echo() 的输出中的 2 个文本之间有空行.

所以,我的问题是,为什么在 MySQLLoginInfo 对象中存储的变量具有正确的值,但是当我尝试访问它们时,它们为空?

任何帮助将不胜感激.

解决方案

在你的 MySQLLoginInfo 构造函数中,你实际上没有设置类变量,只有局部函数变量:

#Loop through lineswhile (($line = fgets($handle)) !== false) {如果 ($i === 0)$this->host = $line;//vs $host = $line;//...}

我建议您参阅关于类属性的文档:><块引用>

在类方法中可以使用->访问非静态属性(对象运算符):$this->property(其中 property 是财产).静态属性通过使用 :: (Double冒号):self::$property.有关更多信息,请参阅静态关键字静态和非静态属性的区别.

Alright, this is my main code:

require "checkpassword.php";
require "mysqllogininfo.php";

# Validate password
if (!validatePassword($_GET["password"])) {
    return;
}

# Get variables
$uuid = $_GET["uuid"];
if (preg_match('/^\d+$/',$_GET["rank"]) == false) {
    die("Rank must be integer");
}
$rank = $_GET["rank"];

# Validate UUID
if ($uuid == null) {
    die ("Supply uuid");
}

# Validate rank
if ($rank == null) {
    die ("Supply rank");
} else if ($rank < 0 || $rank > 6) {
    die ("Invalid rank");
}

# Load MySQL login info
$loginInfo = new MySQLLoginInfo("/var/uniqraft/mysqllogin");

# Debug
# All this displays as just 3 empty lines, so I assume the variables are null <--
echo($loginInfo->host);
echo "<br>";
echo($loginInfo->username);
echo "<br>";
echo($loginInfo->password);
echo "<br>";
echo($loginInfo->dbname);

# Create connection
$connection = mysqli_connect($loginInfo->host, $loginInfo->username, $loginInfo->password, $loginInfo->dbname);

# Check connection
if (mysqli_connect_errno()) {
    die ("Failed to connect to MySQL: " . mysqli_connect_error());
}

As you can see, I'm trying to access the variables host, username, password and dbname in the MySQLLoginInfo object, but they all display as null.

However, I don't think they are actually null though. Because, if we take a look at the MySQLLoginInfo object, we can see I added some debug echo()'s to display the variables, and there we see that they are in fact not null.

class MySQLLoginInfo
{
    # Properties
    public $host;
    public $username;
    public $password;
    public $dbname;

    # Constructor
    function __construct($infoLocation) {
        $handle = fopen($infoLocation, "r", false) or die("Couldn't open $infoLocation");

        $i = 0;
        # Loop through lines
        while (($line = fgets($handle)) !== false) {
            if ($i === 0)
                $host = $line;
            else if ($i === 1)
                $username = $line;
            else if ($i === 2)
                $password = $line;
            else if ($i === 3)
                $dbname = $line;
            else
                break; # Read at max 4 lines
            $i++;
        }
        if ($i < 3) {
            die($infoLocation . " doesn't contain at least 4 lines");
        }

        # These all display the proper values, indicating that they are not null <--
        echo $host;
        echo $username;
        echo $password;
        echo $dbname;
    }
}

The final output is as follows:

localhost mcserver secret_password uniqraft_core

Failed to connect to MySQL: Access denied for user 'www-data'@'localhost' (using password: NO)

Note that there are empty lines between the 2 texts, from the output from the echo()'s in the main code.

So, my questions is, why are the variables stored with proper values in the MySQLLoginInfo object, but when I try to access them they are null?

Any help would be greatly appreciated.

解决方案

No where in your MySQLLoginInfo constructor do you actually set the class variables, only the local function variables:

#Loop through lines
while (($line = fgets($handle)) !== false) {
    if ($i === 0)
        $this->host = $line; // vs $host = $line;
    // ...
}

I refer you to the documentation on Class Properties:

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property. See Static Keyword for more information on the difference between static and non-static properties.

这篇关于当我尝试在 PHP 中访问它时,类变量为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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