0

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?

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I haven't ever used static in php! I guess there is lot of php to master. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.