0

I am working on developing the skills to really understand OOP in PHP. I am struggling with some code. I know it has something to do with the scope of the variables. I've spent some time googling this and on stack overflow and I don't seem to understand what the issue is.

This is the error:

Fatal error: Uncaught Error: Call to a member function dbConnect() on null in /includes/classes/plates.classes.php:6
Stack trace:
#0 /location.php(6): plates->nearbyPlates('San Diego')
#1 {main} thrown in /includes/classes/plates.classes.php on line 6

dbh.classes.php

class Dbh{

  protected function dbConnect(){
    try{
      $username = "";
      $password = "";
      $dbh = new PDO('mysql:host=URL;dbname=DB', $username, $password);
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $dbh;
    }
    catch(PDOException $e){
      print "Error!: " . $e->getMessage() . "<br/>";
      die();
    }
  }
}

plates.classes.php

class plates extends Dbh{

  public function nearbyPlates($city){
    $stmt = dbConnect()->prepare('SELECT * FROM plates WHERE city = ?;');
    $stmt->bindParam('s', $city);
    $stmt->execute();
    $array = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $array;

  }
}

locations.php

<?php
require_once('includes/classes/dbh.classes.php');
require_once('includes/classes/plates.classes.php');

$location = new plates();
$location->nearbyPlates("San Diego");
print_r($location);
?>
Paul T.
  • 4,015
  • 11
  • 22
  • 27
  • 1
    PHP doesn't implicitly return the last value in a function like some other languages do, you have to explicitly `return $dbh` in your `dbConnect()`. (If that's what your intent was...) Also, to refer to class methods from inside that class, you need `$this->dbConnect()`. – Alex Howansky Jan 28 '22 at 22:21

0 Answers0