开发者

php global variables with variable names

开发者 https://www.devze.com 2023-01-26 17:53 出处:网络
I am trying to have a function that among other things declares global variables based on a variable that i give it.

I am trying to have a function that among other things declares global variables based on a variable that i give it. the part that fails is making the variables global

function setGlobalVariable($name) {

    global $name, $arrayname_{$name};
}

any ide开发者_C百科a? thanks :)


Really, stop messing with global variables that way.

Anywaym here's your solution if you really want to do that:

function setGlobalVariable($name) {
    $GLOBALS['arrayname_' . $name] = 'yourvalue';
}


You should not do that. Global variables are in general a sign of poor design. What is it that you are trying to achieve? I am sure that there is a better solution. Besides that, global does not work like that. global makes other variables outside your function locally available. Use $_GLOBAL to create globals.


Take a look at the Registry Pattern (http://martinfowler.com/eaaCatalog/registry.html).

A well-known object that other objects can use to find common objects and services.

There are various PHP implementations, for example Zend_Registry: http://framework.zend.com/manual/en/zend.registry.html


You're almost right, but not quite; a variable variable takes the form of ${"name"}, so what you're looking for is something like global ${"arrayname_$name"};.

http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/c12np38 is fascinating reading on the topic, if you feel so inclined.

It's likely a terrible idea, though, and if you're resorting to that sort of thing, it's a good indication that your code may be poorly designed. Consider refactoring it (for example, to keep a single known array that your other arrays are kept in, and may be referenced by key.)

0

精彩评论

暂无评论...
验证码 换一张
取 消