Chak
Chak

Reputation: 71

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.

Upvotes: 0

Views: 56

Answers (2)

Mathias Dewelde
Mathias Dewelde

Reputation: 705

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

Upvotes: 1

PHP Worm...
PHP Worm...

Reputation: 4224

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

Upvotes: 0

Related Questions