0

I am unclear here! I got error Notice: Undefined variable: filter when running below code!

But when I remove declare public $filter line,It worked !!! Why ?

use Phalcon\Filter;

class Auth extends Component {   
    public $filter;//remove this line is working
    public function initialize() {
        $this->db = $this->getDI()->getShared("db");
        $this->login_db = $this->getDI()->getShared("login_db");
        $this->filter = new Filter();
    }
    public function auth($name) {
    $name = $this->filter->sanitize($name,"string");
    }

    }
Ian
  • 30,182
  • 19
  • 69
  • 107
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
  • Can you post the whole file and a bit more code where it is calling the class and post the whole error with line number and file etc – Brett May 11 '16 at 05:21
  • Looks like you are running `auth` before `initialize`? – yergo May 11 '16 at 07:59

1 Answers1

3

I made a simple test and reproduced the issue. Let me explain what happens here.

  1. auth($name) is a constructor for the Auth class. Yes, this is old constructor style. This method is called when the object is created. initialize() is not called before the object is created and thus the code $this->filter = new Filter(); is not called before auth() method.

  2. If you comment out declaration public $filter and access the property in constructor then the magic __get() method is invoked from parent class \Phalcon\Di\Injectable and the property is taken from DI container. This is why no errors are shown.

  3. If you specify the property public $filter and create the object the constructor (auth() method) is called before initialize() method and thus property is only defined but not initialized. In this case you get the error.

Fatal error: Call to a member function sanitize() on a non-object in /var/www/app/models/Auth.php on line 19

Let me know if you have any questions.

Victor Smirnov
  • 3,450
  • 4
  • 30
  • 49