使用 Phalcon 过滤器时获取未定义的变量?
Getting undefined variable when using Phalcon filter?
我这里不清楚!当 运行 下面的代码出现错误 Notice: Undefined variable: filter
!
但是当我删除 declare 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");
}
}
我做了一个simple test并重现了这个问题。让我解释一下这里发生了什么。
auth($name)
是 Auth
class 的构造函数。是的,这是 old constructor style。创建对象时调用此方法。 initialize()
在创建对象之前没有被调用,因此代码 $this->filter = new Filter();
在 auth()
方法之前没有被调用。
如果您注释掉声明 public $filter
并在构造函数中访问 属性,那么魔术 __get()
方法将从父 class \Phalcon\Di\Injectable
并且 属性 被采用 from DI container。这就是没有显示错误的原因。
如果指定 属性 public $filter
并创建对象,则在 initialize()
方法之前调用构造函数(auth()
方法),因此 属性只是定义了,没有初始化。在这种情况下,您会收到错误消息。
Fatal error: Call to a member function sanitize() on a non-object in
/var/www/app/models/Auth.php on line 19
如果您有任何问题,请告诉我。
我这里不清楚!当 运行 下面的代码出现错误 Notice: Undefined variable: filter
!
但是当我删除 declare 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");
}
}
我做了一个simple test并重现了这个问题。让我解释一下这里发生了什么。
auth($name)
是Auth
class 的构造函数。是的,这是 old constructor style。创建对象时调用此方法。initialize()
在创建对象之前没有被调用,因此代码$this->filter = new Filter();
在auth()
方法之前没有被调用。如果您注释掉声明
public $filter
并在构造函数中访问 属性,那么魔术__get()
方法将从父 class\Phalcon\Di\Injectable
并且 属性 被采用 from DI container。这就是没有显示错误的原因。如果指定 属性
public $filter
并创建对象,则在initialize()
方法之前调用构造函数(auth()
方法),因此 属性只是定义了,没有初始化。在这种情况下,您会收到错误消息。
Fatal error: Call to a member function sanitize() on a non-object in /var/www/app/models/Auth.php on line 19
如果您有任何问题,请告诉我。