无法通过 php 构造函数设置私有变量

问题描述 投票:0回答:1

我正在尝试使用 _construct 方法设置 Account 类的私有属性。我尝试使用

this->
关键字,但它给了我同样的错误。这是我的代码。

<?php

class Account
{
    private $errorArray = array();
    private $userName;
    private $firstName;
    private $lastName;
    private $password;
    private $password2;
    private $role;
    //$userName, $firstName, $lastName, $password, $password2, $role
    function __construct()
    {
        if (isset($_POST['registerSubmit'])) {

            $userName = $_POST['userName'];
            $firstName = $_POST['firstName'];
            $lastName = $_POST['lastName'];
            $password = $_POST['password'];
            $password2 = $_POST['password2'];
            $role = $_POST['role'];
        }
    }
    public function register()
    {
        checkUserName($userName, $errorArray);
        checkFirstName($firstName, $errorArray);
        checkLastName($lastName, $errorArray);
        checkPasswords($password, $password2, $errorArray);
        return $this->errorArray;
    }

错误提示

变量firstName已声明但从未使用。但我显然在 __construct 以及下一个函数中使用了它。

我尝试过:

在构造函数内部甚至在参数中使用

this->
checkUsername() 像这样
checkUserName(this-?$userName, this->errorsArray);

对我来说奇怪的部分是

当我在

$errorArray
函数中返回
register()
时,它没有问题,但是 当我尝试以任何其他方式访问它时,它会给我错误。

有关此问题的任何帮助将不胜感激。

php reference private-members private-methods construct
1个回答
1
投票

我犯的愚蠢错误在于语法。 需要使用

$this->variableName
而不是
this->$VariableName

© www.soinside.com 2019 - 2024. All rights reserved.