使用Phalcon过滤器时获取未定义的变量?

时间:2016-05-11 05:09:51

标签: php phalcon

我不清楚这里!在代码下运行时出现错误Notice: Undefined variable: filter

但当我删除声明public $filter行时,它有效!!!为什么?

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

    }

1 个答案:

答案 0 :(得分:3)

我做了一个simple test并重现了这个问题。让我解释一下这里发生的事情。

  1. location ~ /blog(/.*) { proxy_pass http://public-ip; #server IP where the wordpress installed proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } auth($name)类的构造函数。是的,这是old constructor style。创建对象时调用此方法。在创建对象之前未调用Auth,因此在initialize()方法之前未调用代码$this->filter = new Filter();

  2. 如果您注释掉声明auth()并在构造函数中访问该属性,则会从父类public $filter调用魔术__get()方法并获取该属性{{3} }。这就是没有显示错误的原因。

  3. 如果指定属性\Phalcon\Di\Injectable并创建对象,则在public $filter方法之前调用构造函数(auth()方法),因此仅定义属性但未初始化。在这种情况下,您会收到错误。

  4.   

    致命错误:在非对象中调用成员函数sanitize()   第19行/var/www/app/models/Auth.php

    如果您有任何问题,请与我们联系。