0

I'm a bit confused by PHP. In the example below the only accepted way is to initialise bVar in the constructor. Do i always have to do this if i want to use class properties inside the class itself? Or is my syntax just bad for the purpose if accessing class properties within the class itself?

class test{
protected aVar = "varValue";
protected bVar;
function __construct(){
    $this->bVar = "varValue";
}

function testerFunc(){
    echo $aVar //undefined variable
    echo $this->$aVar //undefined variable
    echo $bvar //works fine
}


}
5
  • I can't imagine that echo $bvar works. If you want to access this variable you have to call it like this: $this->bVar Commented Feb 22, 2019 at 7:20
  • You have a typo where you're trying to echo $aVar. It should be echo $this->aVar; Remove the dollar sign before the variable name. Commented Feb 22, 2019 at 7:21
  • Variables in PHP are represented by a dollar sign followed by the name of the variable! Commented Feb 22, 2019 at 7:24
  • As RainDev says, you also need a dollar sign when you declare the variable in the first place: protected $aVar = "varValue"; Commented Feb 22, 2019 at 7:25
  • Also, all your echo statements lack semicolons. Commented Feb 22, 2019 at 7:27

1 Answer 1

1

Your syntax is bit of a mess:

class test {
    protected $aVar = "varValue";
    protected $bVar;

    function __construct() {
        $this->bVar = "varValue";
    }

    function testerFunc() {
        echo $aVar; //undefined variable
        echo $this->aVar; // varValue (works fine)
        echo $this->bVar; // varValue (works fine)
        echo $bvar; //undefined variable
    }
}
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.