salmane
salmane

Reputation: 4849

php global variables with variable names

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 idea? thanks :)

Upvotes: 1

Views: 910

Answers (4)

Yeroon
Yeroon

Reputation: 3243

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

Upvotes: 1

Chris Heald
Chris Heald

Reputation: 62638

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.)

Upvotes: 0

jwueller
jwueller

Reputation: 30996

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.

Upvotes: 3

ThiefMaster
ThiefMaster

Reputation: 318478

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';
}

Upvotes: 6

Related Questions