My database connection file where I make the connection to the database and return it as an object.
<?php
require('config.php');
class db{
protected function connect(){
try {
$connect = new PDO("sqlsrv:server='.$servername.';database='.$bd.';",$username,$password);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $connect;
} catch (Exception $e) {
die('Error db(connect) '.$e->getMessage());
}
}
}
?>
The class where the query is executed
class Administrator extends db{
function view_count_users(){
try {
$SQL = 'SELECT Count(*)
FROM Users';
$result = $this->connect()->prepare($SQL);
$result->execute();
return $result->fetchAll(PDO::FETCH_OBJ);
} catch (Exception $e) {
die('Error Administrator(view_users) '.$e->getMessage());
} finally{
$result = null;
}
}
function get_view_count_users(){
return $this->view_count_users();
}
The controller where I call the function from the parent that executes the query
<?php
class administratorController extends Administrator{
function count_users(){
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-info shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-info text-uppercase mb-1">Users
</div>
<div class="row no-gutters align-items-center">
<div class="col-auto">
<div class="h5 mb-0 mr-3 font-weight-bold text-gray-800"><?php echo parent::get_view_count_users(); ?></div>
</div>
</div>
</div>
<div class="col-auto">
<i class="far fa-fw fa-calendar-alt fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
<?php
}
}
?>
Error: Whenever I call the function view_count_users I get the error that I can't use $this when not in object context when the query is connecting to the db. Here: $result = $this->connect()->prepare($SQL);
This function is non-static so I can access since the controller is an extend of the db connecting file.
THE complete Error: Fatal error: Uncaught Error: Using $this when not in object context in C:xampphtdocsarchermodelsAdministrator.php:57 Stack trace: #0 C:xampphtdocsarchercontrollersadministratorController.php(61): Administrator::view_count_users() #1 C:xampphtdocsarcherindex.php(72): administratorController::count_users() #2 {main} thrown in C:xampphtdocsarchermodelsAdministrator.php on line 57
question from:
https://stackoverflow.com/questions/65830109/uncaught-error-using-this-when-not-in-object-context-of-a-protected-function-c 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…