0

How do I pass a URL parameter to a class in PHP?

$questionID = isset($_GET['question']) ? ($_GET['question']) : 0;

class Question {    
    public function __construct() {
        $this->id = $questionID;
    }

It's saying $questionID is undefined in the constructor.

Growler
  • 10,676
  • 21
  • 100
  • 224
  • dont use `global`, either feed it in the constructor and set it as an argument or put the ternary operation inside the constructor – Kevin Mar 26 '15 at 01:34

2 Answers2

1

$_GET is globally accessible, but $questinID isn't.

What you can do is either access $_GET from within the class.

class Question {    
    public function __construct() {
        $this->id = isset($_GET['question']) ? $_GET['question'] : 0;
    }
 }

Or pass it to the constructor.

$questionID = isset($_GET['question']) ? ($_GET['question']) : 0;
class Question {    
    public function __construct($questionID) {
        $this->id = $questionID;
    }
}
$question = new Question($questionID);

The second one is the preferred method, since it allows you to create questions in a more flexible way which, for instance, makes it easier to create unit tests.

kba
  • 18,696
  • 5
  • 56
  • 84
  • @Growler you can use global, read this answer: http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why – CMPS Mar 26 '15 at 01:49
1

There are three ways to make the data available:

1. Access the $_GET data in the constructor:

class Question {    
    public function __construct() {
        $this->id = isset($_GET['question']) ? $_GET['question'] : 0;
    }
 }

2. Pass the variable as a constructor parameter:

class Question {    
    public function __construct($questionId) {
        $this->id = $questionID;
    }
}

Then pass the value when you initialize the new Question:

$question = new Question($_GET['question']);

3. Use a setter to set the value after the object is created:

class Question {
    public function setId($questionId) {
        $this->id = $questionId
    }
}

Then set the value after you initialize the question:

$question = new Question();
$question->setId($_GET['question']);

Use the first method if you are absolutely sure that the way you get the ID will never change (this is not common).

Use the second method if you are sure that the class will need the ID in every case.

Use the third method if the class may or may not need the ID, or if you need a way to change the ID during the life of the object.

George Cummins
  • 26,731
  • 6
  • 65
  • 89