Get_global()



  • Ran across this in some production code today (annonymization added)

    function getFOOk() {
    	
    	global $FOO;
    	// x.Xxxxxxx mm_dd-yyyy
    	// Not sure if we really need this function... as we could simply just echo out $certificate_link instead...
    	// But for now... we'll keep it in place.
    	return $FOO;
    }

    ¿Wat?



  •  I want to believe someone is trying to stop people from using $foo directly and move them to a better approach without breaking existing code.

    I want to believe...



  • You are totally $FOOk'd...

    Also, did you forget to anonymize the comments? I see $certificate_link there, which might have been the original variable...



  • Erps, yep, I did indeed forget to anon the comments.

    And yes, I think the idea was to move away from using a global. But it gets even weirder- that global is created by a function defined in the same file fairly close by (which also returns the global's value). So you could just call the function that creates the global in the first place, instead of "getFOOk()", unless maybe the get call happens at a point in the code where some globals used my "setFOOk()" are no longer valid.



  • IMHO it's good code. Keeps the rest of the program from being dependent on a global variable. The caller code doesn't know, or care, where FOO is coming from. Maybe it's recomputed on every call, maybe it's stored in memory (as shown), maybe it's stored on disk and only recomputed once a month. Not the caller's concern.

    I would have coded it (in C++) like something like this:

    FUNCTION int getFOOk()
    {
    	static FOO = -1;
    	if ( FOO < 0 ) FOO = ComputeFOO();
    	return FOO;
    }
    
    Unfortunately static local variables are a bit ugly in PHP; you may have to use something like global $FOO_725563 ( name has a random number just to ensure that it is unique).


Log in to reply