0

Currently I am re-vamping some code that I currently have written something like this:

<?php
global $foo;
$foo = "foo";

class foo{
   function bar(){
      global $foo;
      return $foo."bar";
   }
}

$class = new foo();
echo foo->bar();
//returns 'foobar';
?>

This works, just fine. My question is, is this the correct way to include the variables? Some of my class files have upwards of 20 global variables, that have to be redefined as global in every method that they are used in.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Hydra IO
  • 1,537
  • 1
  • 13
  • 28
  • 4
    You can't declare variables as "public" outside classes, so I doubt it that this works "just fine" :) – nice ass Jan 21 '13 at 01:53
  • I meant global, not public....sorry about that I'm an idiot. – Hydra IO Jan 21 '13 at 01:54
  • 1
    @HydraIO - You're not an idiot, you're human. Well... humans are idiots, so I guess you're right... – Joseph Silber Jan 21 '13 at 01:55
  • 2
    This is what parameters are for. Using global variables like that isn't a good practice and can get very clunky. – Austin Brunkhorst Jan 21 '13 at 01:59
  • 1
    Global variables aren't bad per se (remember `$_GET`?). But 20 sounds like misdesign, or abuse for state variables, or in place of parameters, or business objects. Your example is way too abstract to give proper advise. – mario Jan 21 '13 at 02:03

1 Answers1

3

Avoid global variables when you can. I won't bother repeating here why, as there are many answers on SO explaining why it's considered a bad practice (example).

Instead, pass the variables you need inside your class to your constructor, like:

class foo{

   protected $foo;

   public function __construct($foo){
     $this->foo = $foo;
   }

   public function bar(){
      return $this->foo . "bar";
   }
}

$foo = "foo";
$class = new foo($foo);
echo foo->bar();
Community
  • 1
  • 1
nice ass
  • 16,471
  • 7
  • 50
  • 89
  • Or just pass it as a parameter to `bar()`. This assumes that you have scope to `$foo` when constructing the class. – Austin Brunkhorst Jan 21 '13 at 02:01
  • Out of curiosity, using this method can I use `parent::$foo` in a class that extends `foo`? – Hydra IO Jan 21 '13 at 02:03
  • If he only needs it within `bar()`, then yes, there's no reason to declare it as a property... @Hydra IO: Child classes will inherit any public or protected properties from the parent class(es), so you would access it the same way, using `$this->foo` – nice ass Jan 21 '13 at 02:04
  • this is a perfect resolution. Thank you @OneTrickPony – Hydra IO Jan 21 '13 at 02:07