I'm trying to learn, understand and implement object-oriented PHP. Something's happening which I don't understand, and I would appreciate any guidance or help.
I have the following class with the following properties and method:
class Film
{
public $film_ids;
public $numfilms;
public function getFilms() {
global $dbh;
global $film_ids;
global $numfilms;
$film_ids = array();
new DBConnection;
$sql = "SELECT * FROM films";
$stmt = $dbh->prepare($sql);
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$film_id = $row['film_id'];
$film_ids[] = $film_id;
}
}
$numfilms = count($film_ids);
$dbh = NULL;
}
}
"DBConnection" is a class that allows me to access a MySQL database with the PDO extension.
I also have a view file (view.php) where I instantiate this class and call the method:
$film = new Film;
$film->getFilms();
After all this, I expect to be able to access the property $film_ids
(a simple array) in my view.php file. But when I do a print_r($film_ids)
in view.php, nothing shows up!
What's strange is that when I add print_r($film_ids)
inside the getFilms()
method, the array prints in my browser just fine!
Array ( [0] => 1 [1] => 2 )
So it's obvious that I'm having no trouble accessing the database and calling the getFilms()
method in view.php -- that's not where the problem lies.
The problem seems to have something to do with variable scope -- accessing the method properties outside of the class. The weird thing is, I have all my properties and methods declared as public. Nothing has been declared private or even protected, so this shouldn't be a problem, should it? I even have the properties I want declared as global inside the getFilms()
method.
Can anybody tell me what I may be doing wrong? Thank you so much!