john denver
john denver

Reputation: 47

PHP using class properties inside class

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
}


}

Upvotes: 0

Views: 50

Answers (1)

Rarst
Rarst

Reputation: 2395

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

Upvotes: 1

Related Questions