Help - Search - Members - Calendar
Full Version: Skip Declaring Variable As Global
Zymic Webmaster Forums > Web Design & Development > Server Side Scripting > PHP
_dexi
Is there a way to avoid using the global keyword inside functions, without passing them as a parameter, and still having them available? Something like this:

CODE
<?php
$someVar = new Obj();

// random magic here

function example() {
   echo $someVar->beh;
}

?>


Also, aside from using Obj::beh (which I assume would work based on what I read?)

Thanks
_dexi
Forgot the reason, it was just inconvenient, considering the function is used many times. If there isn't any way out of it then I'll be forced to, it'd just be easier if they could be declared as [super?]globals.

Thanks for the static info though
_dexi
While i'm on the topic, is declaring the member static in any way an advantage (using :: instead of ->) over normal? Aside from not having to add global/pass as a param.
Alex
You don't need to create an instance of the class.
Ed
You could always use the singleton pattern and create a registry like object, for example:

CODE
<?php
class registry
{
   const ERR_PROPERTY_NON_EXISTANT = 1;

   public static $instance;

   private $registry;

   public function __construct($registry)
   {
      if(!is_array($registry))
      {
         $this->registry = array();
      }
      else
      {
         $this->registry = $registry;
      }
   }

   public static function getRegistry($registry = false)
   {
      if(!isset(self::$instance))
      {
         self::$instance = new self($registry);
      }

      return self::$instance;
   }

   public function __get($property)
   {
      if(isset($this->registry[$property]))
      {
         return $this->registry[$property];
      }
      else
      {
         throw new Exception('Registry property does not exist.', self::ERR_PROPERTY_NON_EXISTANT);
      }
   }

   public function __set($property, $value)
   {
      $this->registry[$property] = $value;
   }
}

/*
* Example usage
*/

$set = array(
   'foo' => 'I am foo.',
   'bar' => 'I am bar.'
);

// Notice no 'new' keyword for instantiation
$registry = registry::getRegistry($set);

// Use object's getter to retrieve value
echo $registry->foo, "\n", $registry->bar, "\n";

// set a new registered item (or change an existing) with object's setter
$registry->bork = 'I am bork.';

echo $registry->bork, "\n";
?>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2012 Invision Power Services, Inc.