user3871
user3871

Reputation: 12718

pass URL param to class

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.

Upvotes: 0

Views: 1254

Answers (2)

George Cummins
George Cummins

Reputation: 28906

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.

Upvotes: 1

kba
kba

Reputation: 19466

$_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.

Upvotes: 1

Related Questions