简体   繁体   English

使用Phalcon过滤器时得到未定义的变量?

[英]Getting undefined variable when using Phalcon filter?

I am unclear here! 我不清楚在这里! I got error Notice: Undefined variable: filter when running below code! 我收到错误Notice: Undefined variable: filter在以下代码下运行时Notice: Undefined variable: filter

But when I remove declare public $filter line,It worked !!! 但是当我删除声明public $filter行时,它起作用了!!! 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");
    }

    }

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. auth($name)Auth类的构造函数。 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(); 在创建对象之前不会调用initialize() ,因此代码$this->filter = new Filter(); is not called before auth() method. 不会在auth()方法之前调用。

  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 . 如果您注释掉声明public $filter并访问构造函数中的属性,则从父类\\Phalcon\\Di\\Injectable调用魔术__get()方法,该属性从DI容器获取 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. 如果指定属性public $filter并创建对象,则在initialize()方法之前调用构造函数( auth()方法),因此仅定义但未初始化属性。 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 致命错误:在第19行的/var/www/app/models/Auth.php中的非对象上调用成员函数sanitize()

Let me know if you have any questions. 如果您有任何疑问,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM