0

This is my language class. Is it possible to create array as below? I tried but my compiler is throwing error. If its outside class i can create that array. But why cant i do the same from within class

Does not work

class Language{
    private $LANG = array();

    /*
    ERROR CODE
    1   DATABASE
    2   EMPTY USERNAME AND PASSWORD
    */

    //1   DATABASE
    $LANG[1]["TITLE"] = "DATABASE CONNECTION ERROR";
    $LANG[1]["MESSAGE"] = "PLEASE CONTACT YOUR ADMISTRATOR";

    //2   EMPTY USERNAME AND PASSWORD
    $LANG[2]["TITLE"] = "LOGIN ERROR";
    $LANG[2]["MESSAGE"] = "INVALID USERNAME OR PASSWORD";

    //3   EMPTY QUERY ERROR
    $LANG[3]["TITLE"] = "ERROR";
    $LANG[3]["MESSAGE"] = "UNABLE TO COMMUNICATE WITH SERVER";
}

It works

    private $LANG = array();

    /*
    ERROR CODE
    1   DATABASE
    2   EMPTY USERNAME AND PASSWORD
    */

    //1   DATABASE
    $LANG[1]["TITLE"] = "DATABASE CONNECTION ERROR";
    $LANG[1]["MESSAGE"] = "PLEASE CONTACT YOUR ADMISTRATOR";

    //2   EMPTY USERNAME AND PASSWORD
    $LANG[2]["TITLE"] = "LOGIN ERROR";
    $LANG[2]["MESSAGE"] = "INVALID USERNAME OR PASSWORD";

    //3   EMPTY QUERY ERROR
    $LANG[3]["TITLE"] = "ERROR";
    $LANG[3]["MESSAGE"] = "UNABLE TO COMMUNICATE WITH SERVER";
1

1 Answer 1

2

First. You can't have a code in the class definition outside of method. You need to wrap it in a method.

Second. If you want to operate on class instance's property you have to use the this-> keyword to indicate that.

So your code can look like:

class Language
{
    private $LANG = array();

    function __construct()
    {
        /*
        ERROR CODE
        1   DATABASE
        2   EMPTY USERNAME AND PASSWORD
        */

        //1   DATABASE
        $this->LANG[1]["TITLE"] = "DATABASE CONNECTION ERROR";
        $this->LANG[1]["MESSAGE"] = "PLEASE CONTACT YOUR ADMISTRATOR";

        //2   EMPTY USERNAME AND PASSWORD
        $this->LANG[2]["TITLE"] = "LOGIN ERROR";
        $this->LANG[2]["MESSAGE"] = "INVALID USERNAME OR PASSWORD";

        //3   EMPTY QUERY ERROR
        $this->LANG[3]["TITLE"] = "ERROR";
        $this->LANG[3]["MESSAGE"] = "UNABLE TO COMMUNICATE WITH SERVER";
    }

    function getData()
    {
        return $this->LANG;
    }
}

$lang = new Language();
var_dump($lang->getData());

You can read more about it in the documentation: https://www.php.net/manual/en/language.types.object.php

EDIT: Demo here https://3v4l.org/qVtD9

Sign up to request clarification or add additional context in comments.

1 Comment

Was just making a demo of this very code... you should add it your answer: 3v4l.org/qVtD9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.