I am talking about Common.php file of CodeIgniter framework(system/core folder).
// not required to answer the question though!
I have been going through the code and couldn’t make sense of these particular lines at start of load_class function.
static $_classes = array();
// Does the class exist? If so, we're done...
if (isset($_classes[$class]))
{
return $_classes[$class];
My doubt specifically is, isn’t it pointless to declare a variable to an empty array, and immediately check if some key exists in that array? or am I missing something related to static keyword?
The
staticmodifier in front of that variable means that the value of$_classespersists after each function call.So the first time that function is called,
$_classesdoes not yet exist so it gets created as an empty array.Since its empty, the class doesn’t exist, so it gets loaded and put in the
$_classesvariable.Now when the function terminates, because it is
static, it does not get cleaned up, and its value persists.The next time the function is called, PHP knows it already exists so it is not initialized as an empty array, it still contains what it had the last time the function was called.
See using static variables for more information.