0

As I am learning PHP OOP and I see, there are lots of confusing parts. Here I have a single variable called public $file_link and I trying to assign default value as a superglobal variable. But I can't do like this, it gives a parse error. I am checking the whole file, again and again, to find what's the problem and I see that I cannot assign a default value as a variable in public property. so I need a setter method for public variable. (see my code comment for better understand). should I really need a method to set the value of public property??? (any better way of doing this).

class File_Link {
    public $file_link = 'http://localhost' . $_SERVER["PHP_SELF"];      // CANNOT ASSIGN DEFAULT VALUE
    const FILE_LINK = 'myRoot' . $_SERVER['PHP_SELF'];                  // CANNOT USE LIKE THIS

    public $variable_name = "value";
    public $variable_name_clone = $variable_name; //                    // I GET IT -> I CANNOT USE LIKE THIS BUT IT IS A PUBLIC VARIABLE

    /*
        For a public variable i need use a setter method?????           // FOR A SINGLE LINE I HAVE TO USE THE BELOW CODE WHAT THE >>>>>
    */

    public $host_link = 'http://localhost';                             // THIS WORKS PERFECTLY
    public setFileLink() {
        $this->file_link . $_SERVER["PHP_SELF"];
    }
}

1 Answer 1

3

You can use a constructor to set values, like below

class File_Link
{

    public $file_link;

    public $variable_name = "value";
    public $variable_name_clone;

    public function __construct()
    {
        $this->file_link='http://localhost' . $_SERVER["PHP_SELF"];
        $this->variable_name_clone = $this->variable_name;
    }

}

and constants can't be changed even inside constructor once defined, as the name suggests, that value cannot change during the execution of the script

You may refer : http://php.net/manual/en/language.oop5.properties.php

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

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

Comments

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.