Mark H
Mark H

Reputation: 589

PHP global Variables within classes

I am fairly new to using PHP with classes and wondered if there is a better method for what I'm doing. Basically I am looking for the best way to handle user errors (like "That username is taken" etc).

What I am doing..

In init.php

global $errors;
$errors  = array();
require ...

In classname.php

class Test {
 public function myFunction($username) {

  if ... {
    //Do Something
    global $errors;
    $this->errors = $errors[] = "Username already in use!";
  }

  else ... { 
    global $errors;
    $this->errors = $errors[] = "Username already in use!";
  }
 }
 public function .... {}
}

Basically is there a way I can use the global array without having to re-write global $errors every time? Having to do repeat it just doesn't feel efficient which in my case usually means there is a better way. Any ideas?

Upvotes: 0

Views: 48

Answers (2)

Sammitch
Sammitch

Reputation: 32272

Basically any time you have to declare a variable global there's likely a better way to go about what you're doing that will have you writing clearer, more maintainable code.

Here are two methods I stick to to handle what you're up against.

class Foo {

  // example 1: exceptions
  public function newUser1($username) {
    if( $this->userExists($username) ) {
      throw new Exception("User already exists: $username");
    }
  }

  // example 2: pass-by-reference
  public function newUser2($username, &$errors) {
    if( $this->userExists($username) ) {
      $errors[] = "User already exists: $username";
      return
    }
  }

}

$inst = new Foo();
$errors = array();

// example 1: exception handling
try {
  $foo->newUser1('Sammitch');
} catch ( Exception $e ) {
  $errors[] = $e->getMessage();
}

//example 2: pass-by-reference
$foo->newUser2('Sammitch', $errors);
if( count($errors) > 1 ) {
  // oh noes!
}

The one restriction of Exceptions is that when your throw it execution stops and the exception either goes into the catch block or, if there are no catch block, the exception bubbles up until it becomes a fatal PHP error.

Upvotes: 2

Machavity
Machavity

Reputation: 31644

I would suggest you inject your $errors instead of globalizing it. That way you don't have to track down where it's being set/called/etc

 class Test {
     public function __construct(Array $errors) {
         $this->errors = $errors;
     }
 }

 $test = new Test($errors);

Upvotes: 2

Related Questions