简体   繁体   中英

php static variable initialization doesn't make sense here

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 static modifier in front of that variable means that the value of $_classes persists after each function call.

So the first time that function is called, $_classes does 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 $_classes variable.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM