PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
// CallGlobalCode.php
function something()
{
require_once 'GlobalCode.php'; // GlobalCode is only needed if this function is used
return globalFunction();
}
This is because GlobalCode.php was required inside something() function making the variable definition local to the function rather than global as intended. The call to globalFunction() inside something() works because function definitions are always global.
Constraints:
You are not allowed to modify GlobalCode.php
In CallGlobalCode.php, GlobalCode.php must only be required when it is needed i.e. when something is called so just sticking require_once 'GlobalCode.php' outside of something() is not acceptable.
So the question is how can I fool PHP into thinking GlobalCode.php is in global scope even when it is being called from inside a function without modifying GlobalCode.php itself?
The globals are defined in phputf8 written by Harry Fuecks. I certainly wouldn't write a library in this way (and I'm not) but considering my library depends on phputf8 I don't want to have to modify phputf8 in order for it to work with mine hence constrant
I wrote:You are not allowed to modify GlobalCode.php
If you really must use a global like this, write it directly to the $GLOBALS array. EG
Breaks the first constrant and is obviously what I would do were it not there.
Well, I suppose you could do file_get_contents("GlobalCode.php"), modify it, then eval the resulting string. I wouldn't though.
Yes I did consider that but I happen to agree with you, its pretty manky.
function something()
{
global $globalVar;
require_once 'GlobalCode.php'; // GlobalCode is only needed if this function is used
return globalFunction();
}
Re this bug report - understood and considering fixes - not decided yet. Hadn't foreseen that scenario.
The globals are defined in phputf8 written by Harry Fuecks. I certainly wouldn't write a library in this way (and I'm not) but considering my library depends on phputf8 I don't want to have to modify phputf8 in order for it to work with mine hence constrant
The reason for placing the lookup table globally is for performance - ideally it should only be created once per request. For similar reasons phputf8 prefers functions over classes - anything that save a few milliseconds. Normally abstractions are worth it but when it comes to replacing something as fundamental as PHP's string functions, which tend to get used all over, with userland functions, performance is worth considering.