1

I have really started to look at PHP Classes, and I can not understand why this does not work. I thought if you define a variable in the constructor you can call it by that variable name. That is not the case though(?), let me give you all an example:

class test {

    public function __construct($item) {

        $this->item= $anItem;

    }

    public function callvar() {

        //Does not work
        return $anItem;

    }

    public function callvar() {

        //Works
        return $this->item;

    }

}

So my question is, am I doing something wrong? Or must you call a __construct variable by $this->item?

1 Answer 1

1

$anItem is local variable in construct function, so it isn't a variable for another method. But $this->item is property of test class so that every method in test class can access this property as a global variable

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

3 Comments

Hmm, so there is no other to access a __contruct() variables other than with $this->item?
Personally, I always assign class properties in __contruct() function. Ex: __contruct($p1, $p2) for $this->p1, $this->p2. Then others use $this->p1, $this->p2. __contruct() is only a method
Hmm, that is what I have been doing. I was just wondering if there is a way to shorten it down :) Thank You

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.