Prasanth
Prasanth

Reputation: 5258

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?

Upvotes: 0

Views: 377

Answers (1)

drew010
drew010

Reputation: 69937

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.

Upvotes: 4

Related Questions