Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

reference - Cannot set private variable through constructor php

I am trying to set private properties of Account class using _construct method. I tried using this-> keyword but it gives me the same error. Here is my code.

<?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;
    }

the error says

variable firstName is declared but never used. But I am clearly using it in the __construct and also in the next functions.

I tried:

using this-> inside constructor and even in parameters of checkUsername() like this checkUserName(this-?$userName, this->errorsArray);

the stranges part for me is

when I return $errorArray in register() function it has no problem but when i try to access it in any other way it gives me errors.

Any help regarding this problem will be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The silly mistake i was making was in the syntax. Need to use
$this->variableName instead of this->$Variable name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...