CodeIgniter: system/core/Model.php - Undefined Property
I just ran into a problem where, for whatever reason, the core/Model’s __get()
function calling an unknown property and it was fairly hard to track down what was causing the problem.
The current develop __get()
function reads:
public function __get($key)
{
return get_instance()->$key;
}
A very simple quick fix is to use the @
operator in front of the call - this does not inform the programer of where the error is and suppresses it. Although, this could cause some unexpected problems of it’s own.
public function __get($key)
{
// works but doesn't help the user find where the error is happening.
return @get_instance()->$key or NULL;
}
Reference: http://www.php.net/manual/en/language.operators.errorcontrol.php
To resolve this, and any, undefined property errors the function should read:
function __get($name) {
if (ENVIROMENT != 'production') {
return get_instance()->$name;
}
$CI = & get_instance();
if (isset($CI->name) || property_exists($CI, $name)) {
return $CI->$name;
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'], E_USER_NOTICE);
return null;
}
Note: switched name of var from $key
to $name
due to PHP5’s documentation:
http://www.php.net/manual/en/language.oop5.overloading.php#object.get
EDIT: At the suggestion from @ivantcholakov I’ve changed the above to include (1) an ENVIROMENT
check as well as optimized the isset
and property_exists
for speed.
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Comments: 18 (15 by maintainers)
Commits related to this issue
- [ci skip] Add a note to CI_Model::__get() (issue #3046) — committed to bcit-ci/CodeIgniter by narfbg 10 years ago
That’s a lot of words for a “yes”. 😃