简体   繁体   中英

How Do I Get This PHP Working?

I was hoping the below would print

live
got here

Instead it prints

got here

The code:

$config['env'] = 'live';

sayEnvironment();

function sayEnvironment () {

  echo $config['env'];
  echo 'got here';

}

How do I set this global variable and have everything inside a function access it?

Use global to use global variables inside functions:

$config['env'] = 'live';

sayEnvironment();

function sayEnvironment () {
  global $config;
  echo $config['env'];
  echo 'got here';
}

Or if you have anonymous function, you can use use :

$sayEnvironment2 = function () use ($config) {
    echo $config['env'];
    echo 'got here';
};

$sayEnvironment2(); // must be called AFTER php parser has seen actual function.

Sample

here you go,

$config['env'] = 'live';

sayEnvironment();

function sayEnvironment () {
global $config;
  echo  $config['env'];
  echo 'got here';

}

To answer your question, you can use PHP $GLOBALS for this:

<?php

$GLOBALS['config']['env'] = 'live';

sayEnvironment();

function sayEnvironment () {
  echo $GLOBALS['config']['env'];
  echo 'got here';

}

It's not really considered a good practise to do the above though, but without knowing what you're aiming for it's hard to advise another method. Usually some form of dependency injection would be better.

Docs for it: http://php.net/manual/en/reserved.variables.globals.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM