2

How is it possible to use a class variable as a function parameter?

Example:

class Test {

    protected $img = '';

    protected function foo($var = $this->img)
    {
       ... some code ...
    }

}

Thus is this good practice?

5
  • 1
    You don't. Test if $var is.. something, if it isn't use $this->img, Commented Sep 16, 2016 at 8:54
  • 1
    $this refers to the current object instantiated from the class and therefore sort of doesn't exist until new Test() has been called; you can use a class constant for default data though protected function foo($var = self::IMG) { ... } Commented Sep 16, 2016 at 8:54
  • 2
    You cant have a variable as a default argument value Commented Sep 16, 2016 at 8:55
  • @JonStirling is that good practice? Commented Sep 16, 2016 at 9:27
  • Is it good practise? It totally depends on what you're trying to do. Commented Sep 16, 2016 at 10:02

1 Answer 1

2

I am not 100% sure, but I thing you can't. You can achieve the same like this:

class Test {

    protected $img = '';

    protected function foo($var = null)
    {

        if(is_null($var))
            $var = $this->img;

       ... some code ...
    }

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