[英]Getting undefined variable when using Phalcon filter?
我不清楚在這里! 我收到錯誤Notice: Undefined variable: filter
在以下代碼下運行時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");
}
}
我做了一個簡單的測試,並重現了該問題。 讓我解釋一下這里發生的情況。
auth($name)
是Auth
類的構造函數。 是的,這是舊的構造函數樣式 。 創建對象時調用此方法。 在創建對象之前不會調用initialize()
,因此代碼$this->filter = new Filter();
不會在auth()
方法之前調用。
如果您注釋掉聲明public $filter
並訪問構造函數中的屬性,則從父類\\Phalcon\\Di\\Injectable
調用魔術__get()
方法,該屬性從DI容器獲取 。 這就是為什么沒有顯示錯誤的原因。
如果指定屬性public $filter
並創建對象,則在initialize()
方法之前調用構造函數( auth()
方法),因此僅定義但未初始化屬性。 在這種情況下,您會收到錯誤消息。
致命錯誤:在第19行的/var/www/app/models/Auth.php中的非對象上調用成員函數sanitize()
如果您有任何疑問,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.