Jack jdeoel
Jack jdeoel

Reputation: 4584

Getting undefined variable when using Phalcon filter?

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");
    }

    }

Upvotes: 0

Views: 218

Answers (1)

Victor Smirnov
Victor Smirnov

Reputation: 3780

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.

Upvotes: 3

Related Questions