简体   繁体   中英

Get variable from outside function in a function

I am trying to access an variable outside of a function.

Here is my test code:

function testPARENT() {

$var1 = 'TEST1';
$var2 = 'TEST2';

list_LOOP();
}

function list_LOOP() {

echo $var1

}

I know that I can do like this:

function ($var1, $var2) {}

But that is not what I want to do, because I have a lot variables, and the function should be used as a kind of include function.

There are many (php)-design patterns. For this you could use Singleton (actually this one is an anti-pattern).

Example of Singleton:

<?php
class Registry{
   private static $instance = null;

   private $storage = array();

   public static function getInstance(){
      if( self::$instance === null ){
         self::$instance = new self();
      }
      return self::$instance;
   }

   public function set( $name, $value ){
       $this->storage[$name] = $value;
   }

   public function get( $name ){
       if( isset( $this->storage[$name] )) {
           return $this->storage[ $name ];
       }
       return null;
   }
}

// usage example
$storage = Registry::getInstance();
$storage->set('test', 'testing!');

echo $storage->get('test');

function testing($storage) {
    $storage->set('test', 'TESTING123');
    return $storage->get('test');
}

echo testing($storage);
?>

I added a link below with some extra information.

http://www.phptherightway.com/pages/Design-Patterns.html

Try this code:

function testPARENT() {
   global $var1;
   $var1 = 'TEST1';
   $var2 = 'TEST2';
   list_LOOP();
}

function list_LOOP() {    
  global $var1;    
   echo $var1;    
}
testPARENT();

To accomplish this you have to define your $var1 variable as global

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